forlogic-core 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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 s,useCallback as o,createContext as l,useContext as c,useRef as d,useEffect as u,memo as m,Component as h,forwardRef as p}from"react";import{Slot as f}from"@radix-ui/react-slot";import{cva as g}from"class-variance-authority";import{clsx as v}from"clsx";import{twMerge as x}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as N,format as w}from"date-fns";import{toast as C,Toaster as k}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as S,ChevronDown as A,ChevronUp as D,Check as P,Loader2 as E,Loader2Icon as T,OctagonXIcon as I,TriangleAlertIcon as M,InfoIcon as R,CircleCheckIcon as L,ChevronRight as z,Circle as F,AlertCircle as U,Search as j,FileX as O,Edit as B,PowerOff as $,Power as V,Trash2 as q,Pencil as W,ToggleRight as H,ToggleLeft as G,Plus as Y,LayoutGrid as K,List as Q,Table2 as X,Columns3 as J,GripVertical as Z,Group as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as se,Flame as oe,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 xe,Save as be,Copy as ye,Share as Ne,Upload as we,Download as Ce,HelpCircle as ke,Info as _e,Bell as Se,Clock as Ae,ArrowRight as De,ArrowLeft as Pe,ChevronLeft as Ee,Minus as Te,Filter as Ie,Bookmark as Me,Book as Re,Video as Le,Music as ze,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as $e,Settings as Ve,User as qe,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Je,ExternalLink as Ze,NotebookText as ea,Building2 as aa,LogOut as ta,MoreHorizontal as ra,PanelLeft as na,Edit3 as ia,Code as sa,Heading1 as oa,Heading2 as la,Heading3 as ca,Bold as da,Italic as ua,Underline as ma,Strikethrough as ha,ListOrdered as pa,Highlighter as fa,Link as ga,RemoveFormatting as va,Undo as xa,Redo as ba,ImageIcon as ya,FileSpreadsheet as Na,FileImage as wa,ShieldCheck as Ca,Coffee as ka,CheckCheck as _a,Users as Sa,TriangleAlert as Aa,CheckCircle2 as Da,Hourglass as Pa,MoreVertical as Ea,ArrowUpToLine as Ta,Menu as Ia,Crown as Ma,UserPlus as Ra,MessageSquare as La,Smartphone as za,Paperclip as Fa,CloudUpload as Ua,RotateCcw as ja,Layers as Oa,XCircle as Ba}from"lucide-react";import*as $a from"@radix-ui/react-label";import*as Va from"@radix-ui/react-dialog";import*as qa from"@radix-ui/react-separator";import*as Wa from"@radix-ui/react-alert-dialog";import{useFormContext as Ha,FormProvider as Ga,Controller as Ya,appendErrors as Ka,useForm as Qa}from"react-hook-form";import*as Xa from"@radix-ui/react-select";import*as Ja from"@radix-ui/react-checkbox";import*as Za from"@radix-ui/react-dropdown-menu";import*as et from"@radix-ui/react-tooltip";import*as at from"@radix-ui/react-popover";import{useTranslation as tt,initReactI18next as rt,I18nextProvider as nt}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as it from"@radix-ui/react-scroll-area";import{createClient as st}from"@supabase/supabase-js";import{useQueryClient as ot,useQuery as lt,useMutation as ct,QueryClient as dt,QueryClientProvider as ut}from"@tanstack/react-query";import{useSearchParams as mt,useParams as ht,useNavigate as pt,useLocation as ft,Navigate as gt,Link as vt}from"react-router-dom";import*as xt from"@radix-ui/react-context-menu";import*as bt from"@radix-ui/react-toggle-group";import*as yt from"@radix-ui/react-toggle";import*as Nt from"@radix-ui/react-switch";import wt from"i18next";export{default as i18n}from"i18next";import*as Ct from"@radix-ui/react-collapsible";import*as kt from"@radix-ui/react-tabs";import*as _t from"@radix-ui/react-accordion";import*as St from"@radix-ui/react-avatar";import{DayPicker as At}from"react-day-picker";import{Drawer as Dt}from"vaul";import*as Pt from"@radix-ui/react-hover-card";import*as Et from"@radix-ui/react-navigation-menu";import*as Tt from"@radix-ui/react-progress";import*as It from"@radix-ui/react-radio-group";import*as Mt from"react-resizable-panels";import*as Rt from"@radix-ui/react-slider";import*as Lt from"@radix-ui/react-menubar";import*as zt from"recharts";import{ResponsiveContainer as Ft,XAxis as Ut,YAxis as jt,CartesianGrid as Ot,Tooltip as Bt,Legend as $t,BarChart as Vt,Bar as qt,AreaChart as Wt,Area as Ht,LineChart as Gt,Line as Yt,PieChart as Kt,Pie as Qt,Cell as Xt,ComposedChart as Jt}from"recharts";import{useEditor as Zt,EditorContent as er}from"@tiptap/react";import ar from"@tiptap/starter-kit";import tr from"@tiptap/extension-underline";import rr from"@tiptap/extension-link";import{TextStyle as nr}from"@tiptap/extension-text-style";import{Color as ir}from"@tiptap/extension-color";import sr from"@tiptap/extension-highlight";import{useSensors as or,useSensor as lr,PointerSensor as cr,DndContext as dr,closestCenter as ur}from"@dnd-kit/core";import{SortableContext as mr,rectSortingStrategy as hr,useSortable as pr}from"@dnd-kit/sortable";import{z as fr}from"zod";import{validateFieldsNatively as gr,toNestErrors as vr}from"@hookform/resolvers";const xr="ccjfvpnndclajkleyqkc",br={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},yr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Nr(){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===xr?br:yr}function wr(){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!==xr}const Cr={get oauth(){const e=Nr();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},kr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},_r={debounceDelay:500},Sr=()=>{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},Ar=()=>Sr(),Dr=Sr,Pr=()=>Nr().qualiexApiUrl,Er={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Tr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ir={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Mr={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}`}},Rr=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)}}),Lr=`https://${Nr().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,zr={logo:Ir.isQualiex?`${Lr}/logo-qualiex-white.svg`:`${Lr}/saber-gestao-white.png`,smallLogo:Ir.isQualiex?`${Lr}/logo-forlogic-white.svg`:`${Lr}/small.svg`,favicon:`${Lr}/favicon.png`},Fr=zr.logo,Ur=zr.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=zr.favicon,document.head.appendChild(e)}const jr={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 Or(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Br={date:Or({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Or({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:Or({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},$r={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Vr(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 qr={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:Vr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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 Wr(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 s=i[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(s)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(s));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(s.length)}}}function Hr(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 s=e.valueCallback?e.valueCallback(i[0]):i[0];s=t.valueCallback?t.valueCallback(s):s;return{value:s,rest:a.slice(n.length)}}}const Gr={ordinalNumber:Hr({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},Yr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=jr[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:Br,formatRelative:(e,a,t,r)=>$r[e],localize:qr,match:Gr,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Kr={};function Qr(){return Kr}const Xr=6048e5;function Jr(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 Zr(e){const a=Jr(e);return a.setHours(0,0,0,0),a}function en(e){const a=Jr(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 an(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function tn(e){const a=Jr(e),t=function(e,a){const t=Zr(e),r=Zr(a),n=+t-en(t),i=+r-en(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Jr(e),t=an(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function rn(e,a){const t=Qr(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Jr(e),i=n.getDay(),s=(i<r?7:0)+i-r;return n.setDate(n.getDate()-s),n.setHours(0,0,0,0),n}function nn(e){return rn(e,{weekStartsOn:1})}function sn(e){const a=Jr(e),t=a.getFullYear(),r=an(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=nn(r),i=an(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const s=nn(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=s.getTime()?t:t-1}function on(e){const a=Jr(e),t=+nn(a)-+function(e){const a=sn(e),t=an(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),nn(t)}(a);return Math.round(t/Xr)+1}function ln(e,a){const t=Jr(e),r=t.getFullYear(),n=Qr(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=an(e,0);s.setFullYear(r+1,0,i),s.setHours(0,0,0,0);const o=rn(s,a),l=an(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=rn(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function cn(e,a){const t=Jr(e),r=+rn(t,a)-+function(e,a){const t=Qr(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=ln(e,a),i=an(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),rn(i,a)}(t,a);return Math.round(r/Xr)+1}function dn(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const un={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return dn("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):dn(t+1,2)},d:(e,a)=>dn(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)=>dn(e.getHours()%12||12,a.length),H:(e,a)=>dn(e.getHours(),a.length),m:(e,a)=>dn(e.getMinutes(),a.length),s:(e,a)=>dn(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return dn(Math.trunc(r*Math.pow(10,t-3)),a.length)}},mn="midnight",hn="noon",pn="morning",fn="afternoon",gn="evening",vn="night",xn={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 un.y(e,a)},Y:function(e,a,t,r){const n=ln(e,r),i=n>0?n:1-n;if("YY"===a){return dn(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):dn(i,a.length)},R:function(e,a){return dn(sn(e),a.length)},u:function(e,a){return dn(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 dn(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 dn(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 un.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 dn(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=cn(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):dn(n,a.length)},I:function(e,a,t){const r=on(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):dn(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):un.d(e,a)},D:function(e,a,t){const r=tn(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):dn(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 dn(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 dn(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 dn(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?hn:0===r?mn: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?gn:r>=12?fn:r>=4?pn:vn,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 un.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):un.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):un.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):un.s(e,a)},S:function(e,a){return un.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return yn(r);case"XXXX":case"XX":return Nn(r);default:return Nn(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return yn(r);case"xxxx":case"xx":return Nn(r);default:return Nn(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+bn(r,":");default:return"GMT"+Nn(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+bn(r,":");default:return"GMT"+Nn(r,":")}},t:function(e,a,t){return dn(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return dn(e.getTime(),a.length)}};function bn(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+dn(i,2)}function yn(e,a){if(e%60==0){return(e>0?"-":"+")+dn(Math.abs(e)/60,2)}return Nn(e,a)}function Nn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+dn(Math.trunc(r/60),2)+a+dn(r%60,2)}const wn=(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"})}},Cn=(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"})}},kn={p:Cn,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return wn(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}}",wn(r,a)).replace("{{time}}",Cn(n,a))}},_n=/^D+$/,Sn=/^Y+$/,An=["D","DD","YY","YYYY"];function Dn(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=Jr(e);return!isNaN(Number(a))}const Pn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,En=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Tn=/^'([^]*?)'?$/,In=/''/g,Mn=/[a-zA-Z]/;function Rn(e,a,t){const r=Qr(),n=t?.locale??r.locale??Yr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Jr(e);if(!Dn(o))throw new RangeError("Invalid time value");let l=a.match(En).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,kn[a])(e,n.formatLong)}return e}).join("").match(Pn).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Ln(e)};if(xn[a])return{isToken:!0,value:e};if(a.match(Mn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const c={firstWeekContainsDate:i,weekStartsOn:s,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return Sn.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return _n.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(An.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,xn[i[0]])(o,i,n.localize,c)}).join("")}function Ln(e){const a=e.match(Tn);return a?a[1].replace(In,"'"):e}function zn(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 Fn(e,a){const t=function(e){jn[e]||(jn[e]=Bn?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 jn[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=Un[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 Un={year:0,month:1,day:2,hour:3,minute:4,second:5};const jn={},On=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")),Bn="06/25/2014, 00:00:00"===On||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===On;function $n(e,a,t,r,n,i,s){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,i,s),o}const Vn=36e5,qn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Wn(e,a,t){if(!e)return 0;let r,n,i=qn.timezoneZ.exec(e);if(i)return 0;if(i=qn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Gn(r)?-r*Vn:NaN;if(i=qn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Gn(r,e)?(n=Math.abs(r)*Vn+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(Yn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Yn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return $n(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Hn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Hn(new Date(n),t);if(a===i)return a;n-=i-a;const s=Hn(new Date(n),t);if(i===s)return i;return Math.max(i,s)}(a,n,e);return-i}return NaN}function Hn(e,a){const t=Fn(e,a),r=$n(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 Gn(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Yn={};const Kn={X:function(e,a,t){const r=Qn(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Zn(r);case"XXXX":case"XX":return Jn(r);default:return Jn(r,":")}},x:function(e,a,t){const r=Qn(t.timeZone,e);switch(a){case"x":return Zn(r);case"xxxx":case"xx":return Jn(r);default:return Jn(r,":")}},O:function(e,a,t){const r=Qn(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+Xn(i,2)}(r,":");default:return"GMT"+Jn(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return zn("short",e,t);default:return zn("long",e,t)}}};function Qn(e,a){const t=e?Wn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Xn(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Jn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Xn(Math.floor(r/60),2)+a+Xn(Math.floor(r%60),2)}function Zn(e,a){if(e%60==0){return(e>0?"-":"+")+Xn(Math.abs(e)/60,2)}return Jn(e,a)}function ei(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 ai=36e5,ti=6e4,ri={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 ni(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=ri.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=ri.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=ri.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=ri.YYY[a],r=ri.YYYYY[a];let n=ri.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=ri.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),s=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=ri.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,ci(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=ri.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=li(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=ri.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return ci(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=ri.Www.exec(e),i)return n=parseInt(i[1],10)-1,di(n)?ii(a,n):new Date(NaN);if(i=ri.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return di(n,e)?ii(a,n,e):new Date(NaN)}return null}(i,n);if(null===s||isNaN(s.getTime()))return new Date(NaN);if(s){const e=s.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=ri.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),ui(a)?a%24*ai:NaN;if(r=ri.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),ui(a,t)?a%24*ai+t*ti:NaN;if(r=ri.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return ui(a,t,e)?a%24*ai+t*ti+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Wn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=ei(new Date(e+n)),t=ei(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function ii(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 si=[31,28,31,30,31,30,31,31,30,31,30,31],oi=[31,29,31,30,31,30,31,31,30,31,30,31];function li(e){return e%400==0||e%4==0&&e%100!=0}function ci(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=li(e);if(r&&t>oi[a])return!1;if(!r&&t>si[a])return!1}return!0}function di(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function ui(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const mi=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function hi(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(mi);if(r){const n=ni(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],s=e.replace(a,"'"+Kn[a[0]](n,a,t)+"'");return i?s.substring(0,r-1)+s.substring(r+1):s},a)}return Rn(e,a,t)}(function(e,a,t){const r=Wn(a,e=ni(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 pi={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"}},fi={date:Or({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:Or({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Or({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},gi={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"},vi={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"},xi={ordinalNumber:(e,a)=>Number(e)+"º",era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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"})},bi={ordinalNumber:Hr({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},yi={code:"es",formatDistance:(e,a,t)=>{let r;const n=pi[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:fi,formatRelative:(e,a,t,r)=>1!==a.getHours()?vi[e]:gi[e],localize:xi,match:bi,options:{weekStartsOn:1,firstWeekContainsDate:1}},Ni={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"}},wi={date:Or({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:Or({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Or({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ci={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"},ki={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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"})},_i={ordinalNumber:Hr({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},Si={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=Ni[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:wi,formatRelative:(e,a,t,r)=>{const n=Ci[e];return"function"==typeof n?n(a):n},localize:ki,match:_i,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ai=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Di=[{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"}],Pi=[{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"}],Ei="pt-BR",Ti="dd/MM/yyyy HH:mm",Ii="America/Sao_Paulo",Mi=e=>Ai.find(a=>a.value===e),Ri=e=>Di.find(a=>a.value===e),Li=e=>Pi.find(a=>a.value===e),zi=e=>Ai.some(a=>a.value===e),Fi=e=>Di.some(a=>a.value===e),Ui=e=>Pi.some(a=>a.value===e),ji=()=>{if("undefined"==typeof navigator)return Ei;const e=navigator.language;if(zi(e))return e;const a=e.split("-")[0],t=Ai.find(e=>e.value.startsWith(a));return t?.value||Ei},Oi=()=>{if("undefined"==typeof Intl)return Ii;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Ui(e)?e:Ii}catch{return Ii}},Bi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Ti),$i=()=>{const e=ji();return{locale:e,timezone:Oi(),datetimeFormat:Bi(e)}},Vi={"pt-BR":Si,"en-US":Yr,"es-ES":yi},qi=(e,a=Ti,t=Ii,r=Ei)=>{if(!e)return"";const n=y(e);if(!N(n))return"Data inválida";const i=Vi[r]||Si;try{return hi(n,t,a,{locale:i})}catch(s){return hi(n,Ii,a,{locale:i})}},Wi=(e,a=Ei,t=Ii)=>{if(!e)return"";const r=y(e);if(!N(r))return"Data inválida";const n=Vi[a]||Si;try{return hi(r,t,"PP",{locale:n})}catch(i){return hi(r,Ii,"PP",{locale:n})}},Hi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Gi(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{C.info("Link copiado para a área de transferência")})}function Yi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Ki(...e){return x(v(e))}const Qi=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Qi);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Qi(r);return a}return e},Xi=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Ji=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Zi=g("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"}}),es=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...i},s)=>e(n?f:"button",{className:Ki(Zi({variant:t,size:r,className:a})),ref:s,...i}));es.displayName="Button";const as=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(es,{ref:i,variant:r,size:"icon",className:Ki("h-8 w-8",a),...n,children:t||e(_,{size:16})}));as.displayName="ActionButton";const ts=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:Ki("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}));ts.displayName="Input";const rs=g("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ns=r.forwardRef(({className:a,...t},r)=>e($a.Root,{ref:r,className:Ki(rs(),a),...t}));ns.displayName=$a.Root.displayName;const is=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));is.displayName="Card";const ss=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex flex-col space-y-1.5 p-6",a),...t}));ss.displayName="CardHeader";const os=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Ki("text-2xl font-semibold leading-none tracking-tight",a),...t}));os.displayName="CardTitle";const ls=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));ls.displayName="CardDescription";const cs=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("p-6 pt-0",a),...t}));cs.displayName="CardContent";const ds=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex items-center p-6 pt-0",a),...t}));ds.displayName="CardFooter";const us=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(qa.Root,{ref:i,decorative:r,orientation:t,className:Ki("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));us.displayName=qa.Root.displayName;const ms=Wa.Root,hs=Wa.Trigger,ps=Wa.Portal,fs=r.forwardRef(({className:a,...t},r)=>e(Wa.Overlay,{className:Ki("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}));fs.displayName=Wa.Overlay.displayName;const gs=r.forwardRef(({className:t,...r},n)=>a(ps,{children:[e(fs,{}),e(Wa.Content,{ref:n,className:Ki("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})]}));gs.displayName=Wa.Content.displayName;const vs=({className:a,...t})=>e("div",{className:Ki("flex flex-col space-y-2 text-center sm:text-left",a),...t});vs.displayName="AlertDialogHeader";const xs=({className:a,...t})=>e("div",{className:Ki("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});xs.displayName="AlertDialogFooter";const bs=r.forwardRef(({className:a,...t},r)=>e(Wa.Title,{ref:r,className:Ki("text-lg font-semibold",a),...t}));bs.displayName=Wa.Title.displayName;const ys=r.forwardRef(({className:a,...t},r)=>e(Wa.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));ys.displayName=Wa.Description.displayName;const Ns=r.forwardRef(({className:a,...t},r)=>e(Wa.Action,{ref:r,className:Ki(Zi(),a),...t}));Ns.displayName=Wa.Action.displayName;const ws=r.forwardRef(({className:a,...t},r)=>e(Wa.Cancel,{ref:r,className:Ki(Zi({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));ws.displayName=Wa.Cancel.displayName;const Cs=Va.Root,ks=Va.Trigger,_s=Va.Portal,Ss=Va.Close,As=r.forwardRef(({className:a,...t},r)=>e(Va.Overlay,{ref:r,className:Ki("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}));As.displayName=Va.Overlay.displayName;const Ds={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"}},Ps=r.forwardRef(({className:t,children:n,size:i,variant:s="informative",isDirty:o,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:x,onInteractOutside:b,onEscapeKeyDown:y,...N},w)=>{const[C,k]=r.useState(!1),_=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),D=A?Ds[A]:{},P={...l??D.width?{width:l??D.width}:{},...c??D.minWidth?{minWidth:c??D.minWidth}:{},...d??D.maxWidth?{maxWidth:d??D.maxWidth}:{},...u??D.height?{height:u??D.height}:{},...m??D.minHeight?{minHeight:m??D.minHeight}:{},...h??D.maxHeight?{maxHeight:h??D.maxHeight}:{},...x},E=r.useCallback(e=>{"form"===s&&o?(_.current=e,k(!0)):e()},[s,o]),T="destructive"!==s;return a(_s,{children:[e(As,{}),a(Va.Content,{ref:w,className:Ki("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:P,onInteractOutside:e=>{"form"!==s&&"destructive"!==s?b?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==s)return"form"===s&&o?(e.preventDefault(),void E(()=>{y?.(e)})):void y?.(e);e.preventDefault()},...N,children:[n,T&&a(Va.Close,{onClick:e=>{"form"===s&&o&&(e.preventDefault(),E(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(ms,{open:C,onOpenChange:k,children:a(gs,{children:[a(vs,{children:[e(bs,{children:p}),e(ys,{children:f})]}),a(xs,{children:[e(ws,{onClick:()=>{k(!1),_.current=null},children:g}),e(Ns,{onClick:()=>{k(!1),_.current?.(),_.current=null},children:v})]})]})})]})});Ps.displayName=Va.Content.displayName;const Es=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Ki("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(us,{className:"mt-2"})]});Es.displayName="DialogHeader";const Ts=({className:a,...t})=>e("div",{className:Ki("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Ts.displayName="DialogBody";const Is=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{className:"mb-4"}),e("div",{className:Ki("flex flex-row justify-end gap-2",t),...n,children:r})]});Is.displayName="DialogFooter";const Ms=r.forwardRef(({className:a,...t},r)=>e(Va.Title,{ref:r,className:Ki("text-lg font-semibold leading-none tracking-tight",a),...t}));Ms.displayName=Va.Title.displayName;const Rs=r.forwardRef(({className:a,...t},r)=>e(Va.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Rs.displayName=Va.Description.displayName;const Ls=Ga,zs=r.createContext({}),Fs=({...a})=>e(zs.Provider,{value:{name:a.name},children:e(Ya,{...a})}),Us=()=>{const e=r.useContext(zs),a=r.useContext(js),{getFieldState:t,formState:n}=Ha(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=a;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},js=r.createContext({}),Os=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(js.Provider,{value:{id:i},children:e("div",{ref:n,className:Ki("space-y-2",a),...t})})});Os.displayName="FormItem";const Bs=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=Us();return e(ns,{ref:r,className:Ki(n&&"text-destructive",a),htmlFor:i,...t})});Bs.displayName="FormLabel";const $s=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=Us();return e(f,{ref:t,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...a})});$s.displayName="FormControl";const Vs=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=Us();return e("p",{ref:r,id:n,className:Ki("text-sm text-muted-foreground",a),...t})});Vs.displayName="FormDescription";const qs=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:s}=Us(),o=i?String(i?.message):t;return o?e("p",{ref:n,id:s,className:Ki("text-sm font-medium text-destructive",a),...r,children:o}):null});qs.displayName="FormMessage";const Ws=Xa.Root,Hs=Xa.Group,Gs=Xa.Value,Ys=r.forwardRef(({className:t,children:r,...n},i)=>a(Xa.Trigger,{ref:i,className:Ki("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(Xa.Icon,{asChild:!0,children:e(A,{className:"h-4 w-4 opacity-50"})})]}));Ys.displayName=Xa.Trigger.displayName;const Ks=r.forwardRef(({className:a,...t},r)=>e(Xa.ScrollUpButton,{ref:r,className:Ki("flex cursor-default items-center justify-center py-1",a),...t,children:e(D,{className:"h-4 w-4"})}));Ks.displayName=Xa.ScrollUpButton.displayName;const Qs=r.forwardRef(({className:a,...t},r)=>e(Xa.ScrollDownButton,{ref:r,className:Ki("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));Qs.displayName=Xa.ScrollDownButton.displayName;const Xs=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:s,...o},l)=>e(Xa.Portal,{container:i,children:a(Xa.Content,{ref:l,className:Ki("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:s,...o,children:[e(Ks,{}),e(Xa.Viewport,{className:Ki("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Qs,{})]})}));Xs.displayName=Xa.Content.displayName;const Js=r.forwardRef(({className:a,...t},r)=>e(Xa.Label,{ref:r,className:Ki("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Js.displayName=Xa.Label.displayName;const Zs=r.forwardRef(({className:t,children:r,...n},i)=>a(Xa.Item,{ref:i,className:Ki("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(Xa.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),e(Xa.ItemText,{children:r})]}));Zs.displayName=Xa.Item.displayName;const eo=r.forwardRef(({className:a,...t},r)=>e(Xa.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));eo.displayName=Xa.Separator.displayName;const ao=r.forwardRef(({className:a,...t},r)=>e(Ja.Root,{ref:r,className:Ki("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:Ki("flex items-center justify-center text-current"),children:e(P,{className:"h-4 w-4"})})}));ao.displayName=Ja.Root.displayName;const to=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:Ki("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}));to.displayName="Textarea";const ro=g("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"}}),no=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:Ki(ro({variant:t}),a),...r}));no.displayName="Badge";const io={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function so({size:a="md",className:t}){return e(E,{className:Ki("animate-spin text-muted-foreground",io[a],t)})}function oo({isLoading:r,children:n,className:i,type:s="spinner",size:o="md"}){return r?"overlay"===s?a("div",{className:Ki("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(so,{size:o})})]}):e("div","skeleton"===s?{className:Ki("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Ki("flex items-center justify-center py-8",i),children:e(so,{size:o})}):e(t,{children:n})}const lo=({...a})=>e(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(L,{className:"h-4 w-4"}),info:e(R,{className:"h-4 w-4"}),warning:e(M,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(T,{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}),co=Za.Root,uo=Za.Trigger,mo=Za.Group,ho=Za.Portal,po=Za.Sub,fo=Za.RadioGroup,go=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(Za.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));go.displayName=Za.SubTrigger.displayName;const vo=r.forwardRef(({className:a,...t},r)=>e(Za.SubContent,{ref:r,className:Ki("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}));vo.displayName=Za.SubContent.displayName;const xo=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Za.Portal,{children:e(Za.Content,{ref:n,sideOffset:t,className:Ki("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})}));xo.displayName=Za.Content.displayName;const bo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Za.Item,{ref:n,className:Ki("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}));bo.displayName=Za.Item.displayName;const yo=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(Za.CheckboxItem,{ref:s,className:Ki("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(Za.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),r]}));yo.displayName=Za.CheckboxItem.displayName;const No=r.forwardRef(({className:t,children:r,...n},i)=>a(Za.RadioItem,{ref:i,className:Ki("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(Za.ItemIndicator,{children:e(F,{className:"h-2 w-2 fill-current"})})}),r]}));No.displayName=Za.RadioItem.displayName;const wo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Za.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));wo.displayName=Za.Label.displayName;const Co=r.forwardRef(({className:a,...t},r)=>e(Za.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));Co.displayName=Za.Separator.displayName;const ko=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest opacity-60",a),...t});ko.displayName="DropdownMenuShortcut";const _o=({delayDuration:a=300,...t})=>e(et.Provider,{delayDuration:a,...t}),So=et.Root,Ao=et.Trigger,Do=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(et.Content,{ref:n,sideOffset:t,className:Ki("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}));Do.displayName=et.Content.displayName;const Po=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const s=e(bo,{ref:i,className:Ki("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(_o,{delayDuration:100,children:a(So,{children:[e(Ao,{asChild:!0,children:e("div",{className:"w-full",children:s})}),e(Do,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):s});Po.displayName="DisabledMenuItem";const Eo=at.Root,To=at.Trigger,Io=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},s)=>e(at.Portal,{container:n,children:e(at.Content,{ref:s,align:t,sideOffset:r,className:Ki("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})}));Io.displayName=at.Content.displayName;const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Mo.displayName="Command";const Ro=({children:a,...t})=>e("div",{...t,children:e(Mo,{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})}),Lo=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:Ki("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})}));Lo.displayName="CommandInput";const zo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));zo.displayName="CommandList";const Fo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("py-6 text-center text-sm text-muted-foreground",a),...t}));Fo.displayName="CommandEmpty";const Uo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("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}));Uo.displayName="CommandGroup";const jo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("-mx-1 h-px bg-border",a),...t}));jo.displayName="CommandSeparator";const Oo=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},s)=>e("div",{ref:s,className:Ki("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}));Oo.displayName="CommandItem";const Bo=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function $o({className:a,...t}){return e("div",{className:Ki("animate-pulse rounded-md bg-muted",a),...t})}Bo.displayName="CommandShortcut";const Vo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function qo({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:x,maxDisplayedBadges:b,popoverContainer:y,onOpen:N,onClose:w}){const[C,k]=i(!1),[_,D]=i(""),E=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),T=s(()=>{if(!y)return;let e=y,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},[y]),I=s(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return x?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,x]),M=s(()=>{if(!_)return I;const e=Vo(_);return I.filter(a=>Vo(a.label).includes(e))},[I,_]),R=s(()=>I.filter(e=>E.includes(e.value)),[I,E]),L=e=>{k(e),e?N?.():(D(""),w?.())},z=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?E.filter(a=>a!==e):"")},F=b?R.slice(0,b):R,U=b&&R.length>b?R.length-b:0;return a("div",{className:Ki("space-y-2",v),children:[u&&a(ns,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Eo,{open:C,onOpenChange:L,modal:!1,children:[e(To,{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(),L(!C))},className:Ki("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(no,{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&&z(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>z(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(no,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(es,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Ki("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Io,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:T,collisionBoundary:T,children:a(Mo,{children:[a("div",{className:"relative",children:[e(Lo,{placeholder:p,value:_,onChange:e=>D(e.target.value)}),_&&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:()=>D(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(zo,{children:0===r.length?e(Fo,{children:h}):0===M.length?e(Fo,{children:"Nenhum resultado encontrado"}):e(Uo,{children:M.map(r=>a(Oo,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=E.includes(e)?E.filter(a=>a!==e):[...E,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(P,{className:Ki("mr-2 h-4 w-4",E.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Wo({multiple:t=!1,options:r,items:n,value:i,onChange:s,onValueChange:o,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:x,className:b,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k}){const{t:_}=tt(),S=r||n||[],A=o||s,D=d||_("select_placeholder","Selecione..."),P=h||_("no_results","Nenhum resultado encontrado"),E=p||_("search_placeholder","Pesquisar...");if(v)return a("div",{className:Ki("space-y-2",b),children:[u&&a(ns,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($o,{className:"h-10 w-full"})]});const T="string"==typeof x?x:x instanceof Error?x.message:x?_("error_loading","Erro ao carregar"):void 0;return T?a("div",{className:Ki("space-y-2",b),children:[u&&a(ns,{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(U,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:T})]})]}):e(qo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:D,label:u,icon:m,emptyMessage:P,searchPlaceholder:E,disabled:f,required:g,className:b,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k})}const Ho=r.forwardRef(({className:t,children:r,...n},i)=>a(it.Root,{ref:i,className:Ki("relative overflow-hidden",t),...n,children:[e(it.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(Go,{}),e(it.Corner,{})]}));Ho.displayName=it.Root.displayName;const Go=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(it.ScrollAreaScrollbar,{ref:n,orientation:t,className:Ki("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(it.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Go.displayName=it.ScrollAreaScrollbar.displayName;const Yo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ko(e,a){if(!a)return null;const t=Yo(a),r=[];for(const n of e){const e=Yo(n.label).includes(t),i=n.children?Ko(n.children,a):null,s=i&&i.length>0;(e||s)&&r.push({...n,children:e?n.children:s?i:n.children})}return r}function Qo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Qo(t.children,a);if(e)return e}}}function Xo({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:s,onSelect:o}){const l=t.children&&t.children.length>0,c=s.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:Ki("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(),o(t.value)},children:[e(P,{className:Ki("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:Ki("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?A:z,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Jo({nodes:r,level:i,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=s.has(t.value);return a(n.Fragment,{children:[e(Xo,{node:t,level:i,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Jo,{nodes:t.children,level:i+1,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:c})]},t.value)})})}function Zo({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:x,maxDisplayedBadges:b,popoverContainer:y,onOpen:N,onClose:w}){const{t:C}=tt(),[k,_]=i(!1),[D,P]=i(""),[E,T]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),R=h||C("search_placeholder","Pesquisar..."),L=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),z=s(()=>{if(!y)return;let e=y,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},[y]),F=s(()=>Ko(r,D),[r,D])??r,O=s(()=>D?function(e,a){const t=new Set,r=Yo(a);function n(e){if(!e.children||0===e.children.length)return Yo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Yo(e.label).includes(r)}for(const i of e)n(i);return t}(r,D):new Set,[r,D]),B=D?O:E,$=o(e=>{D||T(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[D]),V=s(()=>L.map(e=>({value:e,label:Qo(r,e)||e})),[L,r]),q=e=>{_(e),e?N?.():(P(""),w?.())},W=o(e=>{if(l)if(t){const a=L.includes(e)?L.filter(a=>a!==e):[...L,e];l(a)}else l(e),_(!1)},[l,t,L]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?L.filter(a=>a!==e):"")},G=b?V.slice(0,b):V,Y=b&&V.length>b?V.length-b:0;if(g)return a("div",{className:Ki("space-y-2",x),children:[d&&a(ns,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($o,{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:Ki("space-y-2",x),children:[d&&a(ns,{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(U,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:Ki("space-y-2",x),children:[d&&a(ns,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Eo,{open:k,onOpenChange:q,modal:!1,children:[e(To,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":k,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),q(!k))},className:Ki("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===V.length&&"text-muted-foreground"),children:[0===V.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(no,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(no,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(es,{variant:"outline",role:"combobox","aria-expanded":k,disabled:p,className:Ki("w-full justify-between min-h-10 h-auto font-normal",0===V.length&&"text-muted-foreground"),children:[0===V.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"}),V[0]?.label]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Io,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:z,collisionBoundary:z,children:[a("div",{className:"flex items-center border-b px-3",children:[e(j,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:R,value:D,onChange:e=>P(e.target.value)}),D&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(Ho,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===F.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(Jo,{nodes:F,level:0,expandedIds:B,onToggleExpand:$,selectedValues:L,onSelect:W})})})]})]})]})}class el{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 s=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),s=!1}const o=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),s=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,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()}}el.LARGE_PAYLOAD_THRESHOLD=1e3;const al="qualiex_access_token",tl="qualiex_id_token",rl="supabase_token",nl="oauth_state",il="oauth_nonce",sl="selected_alias",ol="manual_logout",ll="supabase_project_id",cl={setAccessToken:e=>localStorage.setItem(al,e),getAccessToken:()=>localStorage.getItem(al),setIdToken:e=>localStorage.setItem(tl,e),getIdToken:()=>localStorage.getItem(tl),getSupabaseToken:()=>localStorage.getItem(rl),setOAuthState:e=>sessionStorage.setItem(nl,e),getOAuthState:()=>sessionStorage.getItem(nl),clearOAuthState:()=>sessionStorage.removeItem(nl),setOAuthNonce:e=>sessionStorage.setItem(il,e),getOAuthNonce:()=>sessionStorage.getItem(il),clearOAuthNonce:()=>sessionStorage.removeItem(il),setSelectedAlias:e=>localStorage.setItem(sl,e),getSelectedAlias:()=>localStorage.getItem(sl),clearSelectedAlias:()=>localStorage.removeItem(sl),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:()=>!(!cl.getAccessToken()||!cl.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(ll);return a&&a!==e?(cl.clearAll(),localStorage.setItem(ll,e),!0):(a||localStorage.setItem(ll,e),!1)},setSupabaseToken:e=>{localStorage.setItem(rl,e),cl._clearValidationCache()},areAllTokensValid:()=>{const e=cl.getAccessToken(),a=cl.getIdToken();if(!e||!a)return!1;try{const t=el.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=cl.getAccessToken(),t=cl.getIdToken(),r=cl.getSupabaseToken();return a&&cl.isTokenExpired(a)&&(localStorage.removeItem(al),e=!0),t&&cl.isTokenExpired(t)&&(localStorage.removeItem(tl),e=!0),r&&cl.isTokenExpired(r)&&(localStorage.removeItem(rl),e=!0),e},clearAll:()=>{localStorage.removeItem(al),localStorage.removeItem(tl),localStorage.removeItem(rl),localStorage.removeItem(sl),localStorage.removeItem(ol),sessionStorage.removeItem(nl),sessionStorage.removeItem(il),cl._clearValidationCache()},setManualLogout:()=>localStorage.setItem(ol,"true"),isManualLogout:()=>"true"===localStorage.getItem(ol),clearManualLogout:()=>localStorage.removeItem(ol),isTokenExpired:e=>{try{return el.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{cl._validationCache.isValid=!1,cl._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=cl.getSupabaseToken();if(!e)return!1;if(cl.isTokenExpired(e))return cl._clearValidationCache(),cl._handleExpiredToken(),!1;const a=Date.now();return a-cl._validationCache.timestamp<cl._validationCache.cacheValidityMs?cl._validationCache.isValid:(cl._validationCache.isValid=!0,cl._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>cl.isSupabaseTokenValid()?cl.getSupabaseToken():null,_handleExpiredToken:()=>{cl.clearAll()},extractTokenData:()=>{if(!cl.isSupabaseTokenValid())return null;const e=cl.getSupabaseToken();if(!e)return null;try{const a=el.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 cl._handleExpiredToken(),null}},getCompanyId:e=>{const a=cl.getAccessToken();if(a)try{const t=el.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=cl.extractTokenData();if(t?.companyId)return t.companyId;const r=cl.getIdToken();if(r)try{const a=el.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=[cl.getAccessToken(),cl.getIdToken()];for(const t of a)if(t)try{const a=el.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=cl.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=cl.getIdToken();if(!e)return[];try{const a=el.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 dl=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);C.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){C.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=[]}},ul=import.meta.env.VITE_SUPABASE_URL,ml=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class hl{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ml};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return st(ul,ml,{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 hl.instance||(hl.instance=new hl),hl.instance}getClient(){const e=cl.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!el.isTokenExpired(e)}catch(a){return dl.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function pl(){return hl.getInstance().getClient()}class fl{static async generateToken(e,a,t,r=!1){try{if(!r){const e=cl.getSupabaseToken();if(e&&cl.isSupabaseTokenValid())return e}const n=pl(),{data:i,error:s}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(cl.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 gl{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=cl.getAccessToken(),t=cl.getSelectedAlias();if(!a||!t)return null;const r=await fl.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}gl.regenerationPromise=null,gl.onLogoutCallback=null;class vl{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(cl.clearAll(),window.location.href="/login",!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 xl{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 gl.attemptRegeneration()?(this.isRetrying=!1,!0):(vl.handleError(e),this.isRetrying=!1,!1)}catch(r){return vl.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=cl.getAccessToken();return e?cl.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."}}}xl.isRetrying=!1;const bl=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=xl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=cl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status} ${s.statusText}`);throw e.status=s.status,e.statusCode=s.status,e}return await s.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 dl.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(dl.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 xl.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return dl.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return dl.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 dl.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=cl.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||""})):(dl.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await xl.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 dl.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return dl.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})):(dl.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await xl.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 dl.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return dl.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function yl(e,a){const t=a||Tr.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Nl(e,a){const t=a||Tr.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function wl(e,a){const t=a||Tr.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Cl(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||yl(e.idField),emailField:e.emailField||Nl(e.idField),usernameField:e.usernameField||wl(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:yl(e),emailField:Nl(e),usernameField:wl(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const kl=new Map;class _l{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=kl.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await bl.fetchUsers(e,a);return kl.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(!cl.areAllTokensValid())return e;const t=cl.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Cl(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const s=await this.fetchQualiexUsers(r,n),o=this.indexUsers(s);return e.map(e=>this.enrichEntity(e,i,o))}catch(t){return dl.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Sl=["responsible_name"],Al=e=>Sl.includes(e);function Dl(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:s,schemaName:o,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!cl.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return pl().schema(o).from(n)},u=(e,a,t,r)=>{let n=d().select(s||"*",{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 o=a.includes(".");return o||Al(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,i)=>{const s=Cl(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Al(a)||o||s){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},s=await h.getAll(e);if(!s?.data?.length)return s;const c=await _l.enrichWithUserData(s.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=o?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",s=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?s:-s}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",s=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?s:-s}))(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 _l.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:s,limit:o,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...s}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:s}})(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,s,o),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let x=((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,s,o);if((e=>{if(!c||!l||0===e.length)return!1;const a=Cl(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(x.data)){const e=await m(x.data,t,i,s,o);if(!Array.isArray(e))return e;x={...x,data:e}}return x},async getById(e){const{data:a,error:t}=await d().select(s||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Qi(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={...Qi(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 Pl;const El={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Tl{static async initialize(){try{if(cl.checkProjectMismatch())return{...El};if(!cl.hasAllTokens()||!cl.areAllTokensValid())return cl.clearExpiredTokens(),{...El};const e=cl.getAccessToken(),a=cl.getIdToken();cl.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=cl.extractTokenData(),s=i?.alias;let o=null;if(s&&r.some(e=>e.alias===s))o=s;else{const e=cl.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!cl.isSupabaseTokenValid()&&o&&await gl.attemptRegeneration(),!cl.isSupabaseTokenValid())return{...El};let l=null;if(o){const e=cl.getCompanyId(o),a=r.find(e=>e.alias===o);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:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...El}}}static async loginDev(){try{const e=pl(),{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=cl.generateOAuthState();cl.setOAuthState(e);const a=cl.generateOAuthNonce();cl.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Cr.oauth.authUrl);r.searchParams.set("client_id",Cr.oauth.clientId),r.searchParams.set("response_type",Cr.oauth.responseType),r.searchParams.set("scope",Cr.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=cl.getAccessToken();e!==r&&cl.clearAll()}if(cl.hasAllTokens()){return cl.getValidSupabaseToken()||await gl.attemptRegeneration(!0),!0}const s=r,o=n;if(!s||!o)throw new Error("Tokens não encontrados na URL de callback");cl.setAccessToken(s),cl.setIdToken(o),cl.clearManualLogout();const l=this.extractAliasFromAccessToken(s);if(l)cl.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");cl.setSelectedAlias(e[0].alias)}if(!await gl.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return cl.clearOAuthState(),cl.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){cl.setManualLogout(),cl.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 el.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}}Pl=Tl,gl.setLogoutCallback(()=>{Pl.logout()});const Il=e=>e?.placeId||null,Ml=e=>e?.placeName||null,Rl=l(void 0),Ll=({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=ot()}catch{}const[l,c]=i(!1),m=d(0),h=o(e=>{r(a=>({...a,...e}))},[]),p=o(e=>{r(a=>({...a,isLoading:e}))},[]),f=o(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=o(async e=>{if(e.alias===t.alias)return;const a=++m.current;try{const i=cl.getAccessToken();if(!i)return;const s=await fl.generateToken(i,e.alias,void 0,!0);if(m.current!==a)return;if(!s)return;cl.setSupabaseToken(s),cl.setSelectedAlias(e.alias);const o=cl.extractTokenData(),l=o?.alias||e.alias,c=o?.companyId||cl.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 bl.fetchActiveUsersMap(l,c);if(m.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Il(e),placeName:Ml(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=o(async()=>{const e=await Tl.processCallback();if(e){const e=await Tl.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]),x=o(async()=>{await Tl.logout(),f(),n&&await n.clear()},[f,n]),b=o(e=>{c(e)},[]),y=o(()=>{},[]),N=o(()=>{n&&n.invalidateQueries()},[n]);u(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(async()=>{if(e)if(cl.areAllTokensValid()){if(!cl.isSupabaseTokenValid())try{await gl.attemptRegeneration()||e&&x()}catch(a){e&&x()}}else e&&x()},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,x]),u(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Tl.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&&(vl.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,x]);const w=s(()=>({...t,logout:x,processCallback:v,switchUnit:g,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:b,clearSearch:y,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,x,v,g,l,b,y,N]);return e(Rl.Provider,{value:w,children:a})},zl=()=>{const e=c(Rl);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Fl({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=mt(),u=ot(),{alias:m,userId:h,isAuthenticated:p}=zl(),{t:f}=tt(),g=o(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),x=g("sortField")||kr.sorting.defaultField,b=g("sortDirection")||kr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(kr.pagination.defaultPageSize)),w=v,k=s(()=>({search:w,sortField:x,sortDirection:b,page:y,limit:N,...n}),[w,x,b,y,N,n]),_=o(()=>a.getAll(k),[a,k]),S=lt({queryKey:[e,m,h,k],queryFn:_,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=ct({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.created(t)),l?.()},onError:e=>{C.error(`${Mr.error.create(t)}: ${e.message}`)}}),D=ct({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.updated(t)),l?.()},onError:e=>{C.error(`${Mr.error.update(t)}: ${e.message}`)}}),P=ct({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.deleted(t))},onError:e=>{C.error(`${Mr.error.delete(t)}: ${e.message}`)}}),E=o(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]),T=o(e=>{E({search:e,page:1})},[E]),I=o(e=>{E({sortField:e,sortDirection:x===e&&"asc"===b?"desc":"asc",page:1})},[x,b,E]),M=o(e=>{E({page:e})},[E]),R=o(e=>{E({limit:e,page:1})},[E]),L=o(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[z,F]=i([]),U=o(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=o(()=>{F([])},[]),B=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=ct({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),C.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{C.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=o((e,a)=>{const t=a?a(e):e;e.id?D.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,D]);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||kr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:D?.isPending??!1,isDeleting:P?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:x,sortDirection:b,currentPage:y,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>D.mutate({id:e,data:a}),deleteEntity:P.mutate,save:V,handleSearch:T,handleSort:I,handlePageChange:M,handleItemsPerPageChange:R,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Ul(e){const a=Dl({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)=>Fl({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function jl(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 Ol(e=768){return jl(`(max-width: ${e-1}px)`)}const Bl=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:Ki("w-full caption-bottom text-sm table-fixed",a),...t}));Bl.displayName="Table";const $l=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:Ki("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));$l.displayName="TableHeader";const Vl=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:Ki("[&_tr:last-child]:border-0",a),...t}));Vl.displayName="TableBody";const ql=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:Ki("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));ql.displayName="TableFooter";const Wl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:Ki("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Wl.displayName="TableRow";const Hl=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:Ki("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}));Hl.displayName="TableHead";const Gl=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:Ki("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Gl.displayName="TableCell";const Yl=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:Ki("mt-4 text-sm text-muted-foreground",a),...t}));function Kl({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($o,{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($o,{className:"h-4 w-20"},t))})},t))})]})})}function Ql({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(is,{children:[a(ss,{children:[e($o,{className:"h-4 w-3/4"}),e($o,{className:"h-3 w-1/2"})]}),e(cs,{children:a("div",{className:"space-y-2",children:[e($o,{className:"h-3 w-full"}),e($o,{className:"h-3 w-2/3"})]})})]},r))})}function Xl({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($o,{className:"h-4 w-24"}),e($o,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e($o,{className:"h-10 w-20"}),e($o,{className:"h-10 w-20"})]})]})}function Jl(){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($o,{className:"h-8 w-8 rounded-full"}),e($o,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e($o,{className:"h-8 w-8"}),e($o,{className:"h-8 w-24"})]})]})}function Zl(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e($o,{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($o,{className:"h-4 w-4"}),e($o,{className:"h-4 w-20"})]},r))})]})})}Yl.displayName="TableCaption";const ec={default:O,search:j,error:U};function ac({icon:t,title:r,description:n,action:i,className:s,variant:o="default"}){const l=!!t,c=ec[o];return a("div",{className:Ki("flex flex-col items-center justify-center py-12 px-4 text-center",s),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(es,{onClick:i.onClick,variant:"outline",children:i.label})]})}function tc({children:t,className:n}){const i=r.useRef(null),[s,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&o(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 s?e(_o,{delayDuration:300,children:a(So,{children:[e(Ao,{asChild:!0,children:l}),e(Do,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const rc=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const s="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:Ki("absolute z-20 select-none touch-none","transition-colors duration-150",s&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!s&&["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:Ki("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",s?"h-6 w-0.5":"w-6 h-0.5")})})});rc.displayName="TableResizeHandle";const nc=xt.Root,ic=xt.Trigger,sc=xt.Group,oc=xt.Portal,lc=xt.Sub,cc=xt.RadioGroup,dc=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(xt.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));dc.displayName=xt.SubTrigger.displayName;const uc=r.forwardRef(({className:a,...t},r)=>e(xt.SubContent,{ref:r,className:Ki("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}));uc.displayName=xt.SubContent.displayName;const mc=r.forwardRef(({className:a,...t},r)=>e(xt.Portal,{children:e(xt.Content,{ref:r,className:Ki("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})}));mc.displayName=xt.Content.displayName;const hc=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Item,{ref:n,className:Ki("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}));hc.displayName=xt.Item.displayName;const pc=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(xt.CheckboxItem,{ref:s,className:Ki("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(P,{className:"h-4 w-4"})})}),r]}));pc.displayName=xt.CheckboxItem.displayName;const fc=r.forwardRef(({className:t,children:r,...n},i)=>a(xt.RadioItem,{ref:i,className:Ki("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(F,{className:"h-2 w-2 fill-current"})})}),r]}));fc.displayName=xt.RadioItem.displayName;const gc=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));gc.displayName=xt.Label.displayName;const vc=r.forwardRef(({className:a,...t},r)=>e(xt.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-border",a),...t}));vc.displayName=xt.Separator.displayName;const xc=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});xc.displayName="ContextMenuShortcut";const bc=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:s=!0,canDelete:o=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:B,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:s?$:V,label:s?"Inativar":"Ativar",onClick:i};d.push(e)}if(o&&n){const e={icon:q,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?bo:hc;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:Ki("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))})},yc=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(xo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(bc,{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:s,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),Nc=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>e(_o,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(W,{size:14})})}),e(Do,{children:"Editar"})]}),o.map((t,r)=>{const n=t.icon;return a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(Do,{children:t.label})]},r)}),i&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(s?H:G,{size:14})})}),e(Do,{children:s?"Inativar":"Ativar"})]}),r&&n&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e(q,{size:14})})}),e(Do,{children:"Excluir"})]})]})}),wc=150;function Cc({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,s]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??wc,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??wc,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=d(0),f=d(0),g=o((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??wc)},[r,n]);u(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,o=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));s(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&s(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",o),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",o),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=o(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??wc,e),{});s(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const kc=g("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"}}),_c=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(yt.Root,{ref:i,className:Ki(kc({variant:t,size:r,className:a})),...n}));_c.displayName=yt.Root.displayName;const Sc=r.createContext({size:"default",variant:"default"}),Ac=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},s)=>e(bt.Root,{ref:s,className:Ki("flex items-center justify-center gap-1",a),...i,children:e(Sc.Provider,{value:{variant:t,size:r},children:n})}));Ac.displayName=bt.Root.displayName;const Dc=r.forwardRef(({className:a,children:t,variant:n,size:i,...s},o)=>{const l=r.useContext(Sc);return e(bt.Item,{ref:o,className:Ki(kc({variant:l.variant||n,size:l.size||i}),a),...s,children:t})});Dc.displayName=bt.Item.displayName;const Pc=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:s="",onSearchChange:o,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:x=!1,availableViewModes:b=["table","list","grid"],rightSlot:y,className:N}){const w=d>0,C=t&&n||p.length>0,k=f||x||y,_=i&&o;return C||_||k||c&&w?a("div",{className:Ki("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(es,{onClick:t,children:[e(Y,{size:16,className:"mr-2"}),r||"Novo"]}),p.map((t,r)=>{const n=t.icon;return a(es,{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&&w&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(no,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(_o,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("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(Do,{children:t.label})]},r)}):a(So,{children:[e(Ao,{asChild:!0,children:e(es,{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(Do,{children:"Excluir"})]}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(S,{size:16})})}),e(Do,{children:"Limpar seleção"})]})]})]}),_&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{type:"text",placeholder:l||"Pesquisar",value:s,onChange:e=>o?.(e.target.value),className:"pl-9 w-full"})]})}),k&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,x&&g&&v&&e(Ac,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:b.map(a=>{const t=(e=>{switch(e){case"table":return X;case"list":return Q;case"grid":return K}})(a);return e(Dc,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),y]})]}):null}),Ec=m(({checked:a,onCheckedChange:t})=>e(ao,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function Tc(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 Ic({columns:e,storageKey:a,enabled:t=!0}){const r=s(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?Tc(a)?.hiddenColumns??new Set:new Set),[c,d]=i(()=>{if(!t||!a)return r;const e=Tc(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?Tc(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=o(e=>n.has(e),[n]),v=o(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=o(()=>{l(new Set)},[]),b=o(()=>{if(l(new Set),d(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),y=o((e,a)=>{d(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=o(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),w=o(e=>{h(e),f(new Set)},[]),C=o(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),k=o(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})},[]),_=o((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=o(e=>{h(e?[e]:[]),f(new Set)},[]),D=s(()=>{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]),P=o(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,...s]=t,o=new Map;for(const l of a){const e=String(l[i]??"(vazio)");o.has(e)||o.set(e,[]),o.get(e).push(l)}return Array.from(o.entries()).map(([a,t])=>{const o=n?`${n}|${i}:${a}`:`${i}:${a}`,l=s.length>0?e(t,s,r+1,o):void 0;return{groupKey:o,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:D,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:x,resetColumns:b,columnOrder:c,reorderColumns:y,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:w,addGroupByColumn:C,removeGroupByColumn:k,reorderGroupByColumns:_,getGroupedData:P,collapsedGroups:p,toggleGroupCollapse:N}}function Mc({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=o(()=>{r(null),l(null)},[]),d=o((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 s(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Rc({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:s,showAllColumns:o,reorderColumns:l,groupByColumn:c,setGroupByColumn:u,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[x,b]=i(null),y=d(null),N=new Map(t.map(e=>[String(e.key),e])),w=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{y.current=null,v(null),b(null)};w.some(e=>n(String(e.key)));const k=w.every(e=>!n(String(e.key)));return a(Eo,{children:[e(To,{asChild:!0,children:e(es,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(J,{size:16})})}),a(Io,{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(_o,{delayDuration:300,children:w.map((t,r)=>{const i=String(t.key),o=n(i),d=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{y.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),b(a)})(e,r),onDrop:()=>(e=>{null!==y.current&&y.current!==e&&l(y.current,e),y.current=null,v(null),b(null)})(r),onDragEnd:C,className:Ki("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",x===r&&"border-t-2 border-primary"),children:[e(Z,{size:14,className:"text-muted-foreground shrink-0"}),e(ao,{checked:!o,onCheckedChange:()=>d&&s(i),disabled:!d,className:"shrink-0"}),e("span",{className:Ki("flex-1 truncate",o&&"text-muted-foreground"),children:t.header}),f&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("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(ee,{size:14})})}),e(Do,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(es,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:k?()=>w.filter(e=>!1!==e.hideable).forEach(e=>s(String(e.key))):o,children:k?"Deselecionar todas":"Selecionar todas"}),f&&e(es,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Lc({columns:t,groupByColumns:r,addGroupByColumn:s,removeGroupByColumn:o,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&&s(a)}},className:Ki("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(ee,{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 s=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(no,{variant:"secondary",className:Ki("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",s&&"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(),o(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(S,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const zc=({manager:t,columns:r,onEdit:i,onView:o,onToggleStatus:l,onDelete:c,renderActions:d,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:x=[],hideActionBar:b,showActionBar:y=!0,showSearch:N=!1,searchValue:w,onSearchChange:C,searchPlaceholder:k,bulkActions:_=[],onBulkDelete:S,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:R=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=zl(),j=Ol(),O=void 0!==b?!b:y;u(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=Ic({columns:r,storageKey:L,enabled:R}),$=Mc({enabled:R,onReorder:B.reorderColumns}),V=R?B.visibleColumns:r,{columnWidths:q,isDragging:W,activeColumn:H,handleMouseDown:G}=Cc({columns:V.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=s(()=>(()=>{if(I)return V.map(e=>{const a=q[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=V.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`}})})(),[V,I,q]),K=f||x.length>0||N||h||D||T||R,Q=O&&K,X=S||(()=>{t.bulkDelete?.(t.selectedIds)}),J=a=>e(Gl,{className:"text-center",children:d?d(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(Nc,{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(yc,{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(mc,{className:"w-[160px]",children:e(bc,{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"})}),ee=R?e(Rc,{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(Ql,{count:3}):0===t.entities.length?e(ac,{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(Pc,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:w,onSearchChange:C,searchPlaceholder:k,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:_,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:x,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(nc,{children:[e(ic,{asChild:!0,children:e(is,{className:Ki("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(cs,{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(Ec,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[V.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||o||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(r):e(yc,{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 re=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ne=null!==re,ie=(h?1:0)+V.length+1,se=r=>a(nc,{children:[e(ic,{asChild:!0,children:a(Wl,{className:Ki("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(Gl,{onClick:e=>e.stopPropagation(),children:e(Ec,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),V.map(a=>e(Gl,{className:a.className,children:e(tc,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),J(r)]})}),Z(r)]},r.id),oe=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),s=16*t.level,o=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(Wl,{className:Ki("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(Gl,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${s}px`},children:[e(i?z:A,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?oe(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e(Pc,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:w,onSearchChange:C,searchPlaceholder:k,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:_,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:x,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T}),t.isLoading?e(Kl,{rows:5,columns:V.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Lc,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(Bl,{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($l,{children:a(Wl,{children:[h&&e(Hl,{className:"w-[50px]",children:e(Ec,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),V.map((r,n)=>{const i=I&&!1!==r.resizable,s=H===String(r.key),o=R?$.getDragProps(n,String(r.key)):{},l=$.dragFromIndex===n,c=$.dragOverIndex===n&&$.dragFromIndex!==n;return a(Hl,{className:Ki(r.className,r.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",R&&$.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...o,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?null:"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(rc,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:s})]},String(r.key));var d}),e(Hl,{className:"w-[50px] text-center",children:ee||"Ações"})]})}),e(Vl,{children:0===t.entities.length?e(Wl,{children:e(Gl,{colSpan:ie,className:"h-32",children:e(ac,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ne?oe(re,ie):t.entities.map(se)})]})})]})]})};function Fc(e,a,t,r){const[n,o]=i({}),[l,c]=i({}),d=s(()=>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])}),o(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)=>{o(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 Uc=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],jc=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:s="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(ns,{children:n}),a(Eo,{children:[e(To,{asChild:!0,children:a(es,{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(Io,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ns,{htmlFor:"color-input",children:i}),e(ts,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(ns,{children:s}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Uc.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))})]})]})})]})]}),Oc={Star:Ge,Heart:He,Home:We,User:qe,Settings:Ve,Mail:$e,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:ze,Video:Le,Book:Re,Bookmark:Me,Search:j,Filter:Ie,Edit:B,Trash2:q,Plus:Y,Minus:Te,Check:P,X:S,ChevronDown:A,ChevronUp:D,ChevronLeft:Ee,ChevronRight:z,ArrowUp:ae,ArrowDown:te,ArrowLeft:Pe,ArrowRight:De,Clock:Ae,Bell:Se,AlertCircle:U,Info:_e,HelpCircle:ke,Download:Ce,Upload:we,Share:Ne,Copy:ye,Save:be,FileText:xe,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:oe,Sparkles:se,Award:ie,Trophy:ne,Target:re},Bc=({value:t="Star",onChange:r,label:n,searchLabel:s="Pesquisar"})=>{const[o,l]=i(""),c=Object.entries(Oc).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),d=Oc[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(ns,{children:n}),a(Eo,{children:[e(To,{asChild:!0,children:a(es,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Io,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ns,{htmlFor:"icon-search",children:s}),e(ts,{id:"icon-search",placeholder:s,value:o,onChange:e=>l(e.target.value)})]}),e(Ho,{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))})})]})})]})]})},$c=r.forwardRef(({className:a,...t},r)=>e(Nt.Root,{className:Ki("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(Nt.Thumb,{className:Ki("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")})}));$c.displayName=Nt.Root.displayName;const Vc=(e={})=>{const{user:a,alias:t}=zl(),{enabled:r=!0}=e;return lt({queryKey:["qualiex-users",t],queryFn:()=>bl.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},qc=({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:x,onOpen:b,onClose:y})=>{const{data:N=[],isLoading:w,error:C}=Vc({enabled:h}),k=s(()=>g?N.filter(g):N,[N,g]),_=s(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return k;const t=new Set(k.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return k;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...k,...n]},[k,a]),S=o(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Wo,{multiple:r,value:a??(r?[]:""),onChange:t,options:_,isLoading:w,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:x,onOpen:b,onClose:y})};function Wc({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||""),x=d(null),[b,y]=i(null),N=o(e=>{x.current=e,y(e)},[]),w=s(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:_,handleSubmit:S}=Fc(w,l,void 0,m),A=s(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),D=s(()=>{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(()=>{D!==g&&v(D)},[D,g]);const P=A.find(e=>e.id===D),E=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,s=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?Ki("space-y-2 w-full",t.wrapperClassName):Ki("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:s,children:t.fields?.map(e=>E(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(qc,{value:n||"",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(to,{id:t.name,value:n||"",onChange:e=>{_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ws,{value:String(n),onValueChange:e=>{_(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Ys,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Gs,{placeholder:t.placeholder})}),e(Xs,{children:t.options?.map(a=>e(Zs,{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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Wo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>_(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:b,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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"date",value:String(n),onChange:e=>_(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Ki("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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(jc,{value:n||t.defaultValue||"#3b82f6",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Bc,{value:n||t.defaultValue||"Star",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{_(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:b,...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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);_(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(ao,{id:t.name,checked:!!n,onCheckedChange:e=>_(t.name,e),disabled:t.disabled}),a(ns,{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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($c,{id:t.name,checked:!!n,onCheckedChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"text",value:n||"",onChange:e=>{_(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)}},T=o(()=>{if(!P)return null;if(P.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(P.component){const a=P.component;return e(a,{formData:C,updateField:_,errors:k,users:f,disabled:P.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:P.fields.map(E)})},[P,C,_,k,f,E]),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(es,{variant:D===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:[T(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(es,{type:"button",variant:"outline",onClick:u,children:"Cancelar"}),e(es,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(Cs,{open:m,onOpenChange:e=>{!1===e&&!0===m&&u()},children:a(Ps,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(Es,{showSeparator:!0,children:[e(Ms,{children:t}),e(Rs,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function Hc({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:s,onPageChange:o,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=tt();if(0===i)return null;const u=(r-1)*s+1,m=Math.min(r*s,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(Ws,{value:String(s),onValueChange:e=>l(Number(e)),children:[e(Ys,{className:"h-8 w-[70px]",children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"10",children:"10"}),e(Zs,{value:"25",children:"25"}),e(Zs,{value:"50",children:"50"}),e(Zs,{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(es,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(es,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ee,{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(es,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(es,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function Gc({manager:a}){return e(Hc,{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 Yc={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Kc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Qc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Xc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:s=!1,className:o}){return e("div",{className:Ki("flex","column"===t?"flex-col":"flex-row",Yc[r],Kc[n],Qc[i],s&&"flex-wrap",o),children:a})}function Jc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:s}=zl(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!s&&a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(ts,{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(Ws,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(Ys,{className:"w-[180px]",children:e(Gs,{placeholder:t.placeholder})}),e(Xs,{children:t.options.map(a=>e(Zs,{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}`)}),o&&a(es,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(Xc,{direction:"column",gap:"md",className:"mb-6",children:e(Xc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Zc({manager:t,config:r,formSections:n,onSave:s,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=zl(),[d,m]=mt(),[h,p]=i(!1),[f,g]=i(null),[v,x]=i({isOpen:!1,entityId:null,entityName:""}),[b,y]=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,w="function"==typeof t?.deleteEntity?e=>{x({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{x({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,_=(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(Pc,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{y({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:_,filters:r.filters&&r.filters.length>0?e(Jc,{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(zc,{manager:t,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:o,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(Gc,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(Wc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{s(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(Cs,{open:v.isOpen,onOpenChange:C,children:a(Ps,{size:"sm",variant:"destructive",children:[e(Es,{showSeparator:!0,children:e(Ms,{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(Is,{children:[e(es,{variant:"outline",onClick:C,children:"Cancelar"}),e(es,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),x({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(Cs,{open:b.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:a(Ps,{size:"sm",variant:"destructive",children:[e(Es,{showSeparator:!0,children:e(Ms,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.count})," ",1===b.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),e(es,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),y({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function ed(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:s,onToggleStatus:o}=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:s||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(Zc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:o,defaultSort:n.defaultSort})}}function ad(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 td(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:nd(e),label:nd(e),...rd(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 rd(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 nd(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const id=({children:r})=>{const{isAuthenticated:i,isLoading:s}=zl();if(n.useEffect(()=>{if(s)return;if(i)return;if(cl.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=Ar(),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 Tl.loginDev():Tl.loginProd()})()},[i,s]),s&&!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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Carregando..."})}),a(cs,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Processando..."})}),a(cs,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(cs,{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:Ar()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function sd(e={}){const{paramName:a="alias"}=e,t=ht(),{alias:r,companies:n}=zl(),i=t[a]||null;return s(()=>{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 od({children:r,paramName:n="alias"}){const s=pt(),l=ft(),c=ht(),{alias:m,isAuthenticated:h,isLoading:p,switchUnit:f}=zl(),{urlAlias:g,isAliasMismatch:v,isValidAlias:x,isMissing:b,matchedCompany:y}=sd({paramName:n}),[N,w]=i(!1),C=d(!1),k=n in c,_=o(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),s=n.findIndex(e=>e===a);if(s>=0)return n[s]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return u(()=>{if(k&&!p&&h&&m&&!C.current)if(b)s(_(m),{replace:!0});else if(!g||x){if(v&&y&&!C.current){(async()=>{C.current=!0,w(!0);try{await f(y)}catch(e){m&&s(_(m),{replace:!0})}finally{C.current=!1,w(!1)}})()}}else s(_(m),{replace:!0})},[k,p,h,m,b,g,x,v,y,f,_,s]),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(so,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}function ld(){const{alias:a}=zl(),{pathname:t,search:r,hash:n}=ft();return a?e(gt,{to:`/${a}${t}${r}${n}`,replace:!0}):null}const cd=g("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"}}),dd={info:_e,warning:_e,danger:Xe,success:Qe},ud=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...s},o)=>{const l=dd[r||"info"];return a("div",{ref:o,role:"alert",className:Ki(cd({variant:r}),t),...s,children:[n&&e(l,{className:"h-4 w-4"}),i]})});ud.displayName="Alert";const md=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:Ki("mb-1 font-medium leading-none tracking-tight",a),...t}));md.displayName="AlertTitle";const hd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("text-sm [&_p]:leading-relaxed",a),...t}));hd.displayName="AlertDescription";const pd=()=>{const{processCallback:r}=zl(),n=pt(),[s,o]=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 o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const d=async()=>{c(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",s?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:a(os,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(U,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(cs,{className:"space-y-4",children:[e(ud,{variant:"danger",children:e(hd,{children:s})}),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(es,{onClick:d,disabled:l,className:"flex-1",children:a(t,l?{children:[e(so,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Je,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(es,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(cs,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(so,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},fd=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(cs,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(es,{onClick:async()=>{Ar()?await Tl.loginDev():Tl.loginProd()},className:"w-full",size:"lg",children:Ar()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),gd=l(void 0);function vd({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);u(()=>{c(t)},[t]);const d=o(()=>n({}),[]),m=s(()=>({metadata:r,setMetadata:n,clearMetadata:d,headerActions:l,setHeaderActions:c}),[r,d,l]);return e(gd.Provider,{value:m,children:a})}function xd(){const e=c(gd);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function bd(e){const{setMetadata:a,clearMetadata:t}=xd(),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 yd(e){return{queryClient:e.queryClient||new dt({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Nd={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"},wd={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"},Cd={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 kd(e,a){wt.addResourceBundle(e,"app",a,!0,!0)}wt.use(rt).init({resources:{"pt-BR":{core:Nd},"en-US":{core:wd},"es-ES":{core:Cd}},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 _d=l(void 0),Sd={locale:Ei,timezone:Ii,datetimeFormat:Ti},Ad=async()=>{},Dd=({children:a})=>e(_d.Provider,{value:{...Sd,setLocale:Ad,setTimezone:Ad,setDatetimeFormat:Ad,isLoading:!1},children:a}),Pd=()=>{const e=c(_d);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},Ed=l({moduleAlias:null});function Td({moduleAlias:a=null,children:t}){return e(Ed.Provider,{value:{moduleAlias:a},children:t})}function Id(){return c(Ed)}const Md=Ct.Root,Rd=Ct.CollapsibleTrigger,Ld=Ct.CollapsibleContent;class zd extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=dl.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),C.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;dl.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=dl.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(is,{className:"w-full max-w-2xl",children:[a(ss,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(os,{children:"Algo deu errado"})]}),a(cs,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Md,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Rd,{asChild:!0,children:a(es,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(A,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Ld,{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(Ho,{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(es,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(ye,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(es,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Fd=kt.Root,Ud=r.forwardRef(({className:a,...t},r)=>e(kt.List,{ref:r,className:Ki("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Ud.displayName=kt.List.displayName;const jd=r.forwardRef(({className:a,...t},r)=>e(kt.Trigger,{ref:r,className:Ki("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}));jd.displayName=kt.Trigger.displayName;const Od=r.forwardRef(({className:a,...t},r)=>e(kt.Content,{ref:r,className:Ki("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function Bd({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 $d({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 Vd({educaUrl:t="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i}){const s=Yi(t||n||"https://educacao.sabergestao.com.br/{alias}/fe",i);return a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{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:s,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(Ze,{className:"h-3.5 w-3.5"})]})]}),e(Bd,{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(Ze,{className:"h-3.5 w-3.5"})]})]}),e($d,{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(Ze,{className:"h-3.5 w-3.5"})]})]}),e(ea,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}Od.displayName=kt.Content.displayName;const qd=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias={alias}"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias={alias}"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function Wd({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:Ki("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 Hd(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 Gd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:s}){const o=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=Hd(d,o),p=Hd(m,o),f=(e,a)=>{a?r?.(e):s?.(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(Wd,{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(Wd,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function Yd({onModuleClick:t,contractedModules:r,onModuleInterest:n,nonContractedUrl:s="https://qualiex.com/",educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c,alias:d}){const[u,m]=i("qualiex"),h=e=>{t?.(e)},p=e=>{window.open(s,"_blank","noopener,noreferrer"),n?.(e)};return a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Fd,{value:u,onValueChange:m,className:"flex-1 flex flex-col min-h-0",children:[e(Ud,{className:"w-fit shrink-0",children:qd.map(e=>a(jd,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),qd.map(a=>e(Od,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(Gd,{modules:a.modules,onModuleClick:h,contractedModules:"qualiex"===a.id?r:void 0,onModuleInterest:p})},a.id))]}),e(Vd,{educaUrl:o,saberGestaoUrl:l,wikiUrl:c,alias:d})]})}const Kd={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},Qd=6e5;function Xd(e){const{moduleAlias:a}=Id(),{alias:t,user:r,isAuthenticated:n}=zl(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=lt({queryKey:["qualiex-associations",l,t],queryFn:()=>bl.fetchUserAssociations(l,t),enabled:c,staleTime:Qd,gcTime:12e5}),m=s(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=o(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Kd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:s(()=>!i||h(i),[i,h]),isLoading:c&&u,role:s(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function Jd(e){const{association:a}=Xd();return s(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=qd.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Kd[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Zd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=zl(),u=Jd(i);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(Es,{className:"sr-only",children:e(Ms,{children:"Módulos"})}),e(Yd,{onModuleClick:e=>{n?n(e):e.url&&Gi(Yi(e.url,d||void 0))},contractedModules:u,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:c,alias:d||void 0})]})})}function eu({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:x="lg",children:b}){const y=s(()=>{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(Cs,{open:t,onOpenChange:v?void 0:r,children:a(Ps,{size:x,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(Ms,{children:"Parece que você não tem acesso a essa página"}),e(Rs,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[y.length>1&&a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(aa,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(A,{className:"h-3 w-3 shrink-0"})]})}),e(xo,{align:"end",className:"max-h-[300px] overflow-auto",children:y.map(t=>a(bo,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(aa,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(no,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(co,{children:[e(uo,{asChild:!0,children:a(es,{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(qe,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(A,{className:"h-3 w-3"})]})}),a(xo,{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(Co,{}),a(bo,{onClick:h,children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),b?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:b}),e(Vd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g,alias:u})]}):e(Yd,{onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,alias:u})]})})}function au(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function tu({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=Xd(),{user:g,alias:v,companies:x,isAuthenticated:b,isLoading:y,logout:N,switchUnit:w}=zl(),C=Jd(r),k=s(()=>x?.length?v&&x.find(e=>e.alias===v)||x[0]:null,[x,v]),_=s(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),S=o(e=>{const a=x?.find(a=>a.alias===e.alias);a&&w(a)},[w,x]),A=o(e=>{n?n(e):e.url&&Gi(Yi(e.url,v||void 0))},[n,v]),D=s(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>au(e,[a]));return a?m[a]:void 0},[m]);return y||!b||u?.length&&au(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(so,{size:"lg"})}):h?e(t,{children:a}):e(eu,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:k?.name,units:_,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:D})}function ru({title:t,description:r,image:n,icon:i,ctaLabel:s="Quero conhecer mais",onCtaClick:o,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||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}):o?a(es,{onClick:o,size:"lg",className:"gap-2",children:[e(se,{className:"h-4 w-4"}),s]}):null]})}function nu({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:s}){const[o]=n.useState(()=>new dt({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??o;return n.useEffect(()=>{if(s)for(const[e,a]of Object.entries(s))kd(e,a)},[s]),e(zd,{children:e(nt,{i18n:wt,children:e(ut,{client:l,children:e(Ll,{children:e(Dd,{children:e(Td,{moduleAlias:r,children:e(tu,{...i,children:a})})})})})})})}const iu=_t.Root,su=r.forwardRef(({className:a,...t},r)=>e(_t.Item,{ref:r,className:Ki("border-b",a),...t}));su.displayName="AccordionItem";const ou=r.forwardRef(({className:t,children:r,...n},i)=>e(_t.Header,{className:"flex",children:a(_t.Trigger,{ref:i,className:Ki("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(A,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ou.displayName=_t.Trigger.displayName;const lu=r.forwardRef(({className:a,children:t,...r},n)=>e(_t.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:Ki("pb-4 pt-0",a),children:t})}));lu.displayName=_t.Content.displayName;const cu=r.forwardRef(({className:a,...t},r)=>e(St.Root,{ref:r,className:Ki("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));cu.displayName=St.Root.displayName;const du=r.forwardRef(({className:a,...t},r)=>e(St.Image,{ref:r,className:Ki("aspect-square h-full w-full",a),...t}));du.displayName=St.Image.displayName;const uu=r.forwardRef(({className:a,...t},r)=>e(St.Fallback,{ref:r,className:Ki("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));uu.displayName=St.Fallback.displayName;const mu=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));mu.displayName="Breadcrumb";const hu=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:Ki("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));hu.displayName="BreadcrumbList";const pu=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Ki("inline-flex items-center gap-1.5",a),...t}));pu.displayName="BreadcrumbItem";const fu=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?f:"a",{ref:n,className:Ki("transition-colors hover:text-foreground",t),...r}));fu.displayName="BreadcrumbLink";const gu=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Ki("font-normal text-foreground",a),...t}));gu.displayName="BreadcrumbPage";const vu=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Ki("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});vu.displayName="BreadcrumbSeparator";const xu=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:Ki("flex h-9 w-9 items-center justify-center",t),...r,children:[e(ra,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});xu.displayName="BreadcrumbEllipsis";const bu=g("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"}}),yu=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:Ki(bu({orientation:t}),a),...r}));function Nu({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(At,{showOutsideDays:r,className:Ki("p-3 pointer-events-auto",a),locale:Si,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:Ki(Zi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Ki(Zi({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:Ki(Zi({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?Ee:z,{className:"h-4 w-4"})},...n})}yu.displayName="ButtonGroup",Nu.displayName="Calendar";const wu={Root:function({children:a,className:t}){return e("div",{className:Ki("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(is,{className:Ki("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(cs,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:Ki("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 Cu({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:s,disabledDates:o}){return a(Eo,{children:[e(To,{asChild:!0,children:a(es,{variant:"outline",disabled:i,className:Ki("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",s),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?w(t,"d 'de' MMMM 'de' yyyy",{locale:Si}):e("span",{children:n})]})}),e(Io,{className:"w-auto p-0",align:"start",children:e(Nu,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const ku=({shouldScaleBackground:a=!0,...t})=>e(Dt.Root,{shouldScaleBackground:a,...t});ku.displayName="Drawer";const _u=Dt.Trigger,Su=Dt.Portal,Au=Dt.Close,Du=r.forwardRef(({className:a,...t},r)=>e(Dt.Overlay,{ref:r,className:Ki("fixed inset-0 z-50 bg-black/80",a),...t}));Du.displayName=Dt.Overlay.displayName;const Pu=r.forwardRef(({className:t,children:r,...n},i)=>a(Su,{children:[e(Du,{}),a(Dt.Content,{ref:i,className:Ki("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]})]}));Pu.displayName="DrawerContent";const Eu=({className:a,...t})=>e("div",{className:Ki("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Eu.displayName="DrawerHeader";const Tu=({className:a,...t})=>e("div",{className:Ki("mt-auto flex flex-col gap-2 p-4",a),...t});Tu.displayName="DrawerFooter";const Iu=r.forwardRef(({className:a,...t},r)=>e(Dt.Title,{ref:r,className:Ki("text-lg font-semibold leading-none tracking-tight",a),...t}));Iu.displayName=Dt.Title.displayName;const Mu=r.forwardRef(({className:a,...t},r)=>e(Dt.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Mu.displayName=Dt.Description.displayName;const Ru={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))]"},Lu={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function zu({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:Ki("grid",Ru[t],Lu[r],n),children:a})}const Fu=Pt.Root,Uu=Pt.Trigger,ju=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(Pt.Content,{ref:i,align:t,sideOffset:r,className:Ki("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}));ju.displayName=Pt.Content.displayName;const Ou=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:Ki("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}));Ou.displayName="InputGroup";const Bu=g("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"}}),$u=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:Ki(Bu({align:t}),a),...r}));$u.displayName="InputGroupAddon";const Vu=g("",{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"}}),qu=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(es,{ref:i,"data-slot":"input-group-button",variant:r,className:Ki(Vu({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));qu.displayName="InputGroupButton";const Wu=r.forwardRef(({className:a,...t},r)=>e(ts,{ref:r,"data-slot":"input-group-control",className:Ki("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Wu.displayName="InputGroupInput";const Hu=r.forwardRef(({className:a,...t},r)=>e(to,{ref:r,"data-slot":"input-group-control",className:Ki("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Hu.displayName="InputGroupTextarea";const Gu=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:Ki("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Gu.displayName="H1";const Yu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:Ki("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));Yu.displayName="H2";const Ku=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Ki("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Ku.displayName="H3";const Qu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:Ki("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Qu.displayName="H4";const Xu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Xu.displayName="P";const Ju=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-xl text-muted-foreground",a),...t}));Ju.displayName="Lead";const Zu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("text-lg font-semibold",a),...t}));Zu.displayName="Large";const em=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:Ki("text-sm font-medium leading-none",a),...t}));em.displayName="Small";const am=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));am.displayName="Muted";const tm=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:Ki("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));tm.displayName="InlineCode";const rm=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:Ki("mt-6 border-l-2 pl-6 italic",a),...t}));rm.displayName="Blockquote";const nm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Ki("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));nm.displayName="List";const im=r.forwardRef(({className:t,children:r,...n},i)=>a(Et.Root,{ref:i,className:Ki("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(mm,{})]}));im.displayName=Et.Root.displayName;const sm=r.forwardRef(({className:a,...t},r)=>e(Et.List,{ref:r,className:Ki("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));sm.displayName=Et.List.displayName;const om=Et.Item,lm=g("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"),cm=r.forwardRef(({className:t,children:r,...n},i)=>a(Et.Trigger,{ref:i,className:Ki(lm(),"group",t),...n,children:[r," ",e(A,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));cm.displayName=Et.Trigger.displayName;const dm=r.forwardRef(({className:a,...t},r)=>e(Et.Content,{ref:r,className:Ki("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}));dm.displayName=Et.Content.displayName;const um=Et.Link,mm=r.forwardRef(({className:a,...t},r)=>e("div",{className:Ki("absolute left-0 top-full flex justify-center"),children:e(Et.Viewport,{className:Ki("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})}));mm.displayName=Et.Viewport.displayName;const hm=r.forwardRef(({className:a,...t},r)=>e(Et.Indicator,{ref:r,className:Ki("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 pm({items:r,maxItems:n=3,className:i}){const s=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(mu,{className:i,children:e(hu,{children:s.map((r,n)=>{const i=o&&1===n;return a(pu,{children:[!(0===n)&&e(vu,{}),i&&a(t,{children:[e(xu,{}),e(vu,{})]}),r.isCurrentPage?e(gu,{children:r.label}):e(fu,{asChild:!0,children:e(vt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function fm(){const e=ft();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,s=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:s,href:i?void 0:r,isCurrentPage:i})}),t})()}hm.displayName=Et.Indicator.displayName;const gm=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:Ki("mx-auto flex w-full justify-center",a),...t});gm.displayName="Pagination";const vm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Ki("flex flex-row items-center gap-1",a),...t}));vm.displayName="PaginationContent";const xm=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Ki("",a),...t}));xm.displayName="PaginationItem";const bm=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:Ki(Zi({variant:t?"outline":"ghost",size:r}),a),...n});bm.displayName="PaginationLink";const ym=({className:t,...r})=>a(bm,{"aria-label":"Go to previous page",size:"default",className:Ki("gap-1 pl-2.5",t),...r,children:[e(Ee,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});ym.displayName="PaginationPrevious";const Nm=({className:t,...r})=>a(bm,{"aria-label":"Go to next page",size:"default",className:Ki("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});Nm.displayName="PaginationNext";const wm=({className:t,...r})=>a("span",{"aria-hidden":!0,className:Ki("flex h-9 w-9 items-center justify-center",t),...r,children:[e(ra,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});wm.displayName="PaginationEllipsis";const Cm=r.forwardRef(({className:a,value:t,...r},n)=>e(Tt.Root,{ref:n,className:Ki("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(Tt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Cm.displayName=Tt.Root.displayName;const km=r.forwardRef(({className:a,...t},r)=>e(It.Root,{className:Ki("grid gap-2",a),...t,ref:r}));km.displayName=It.Root.displayName;const _m=r.forwardRef(({className:a,...t},r)=>e(It.Item,{ref:r,className:Ki("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(It.Indicator,{className:"flex items-center justify-center",children:e(F,{className:"h-2.5 w-2.5 fill-current text-current"})})}));_m.displayName=It.Item.displayName;const Sm=({className:a,...t})=>e(Mt.PanelGroup,{className:Ki("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Am=Mt.Panel,Dm=({withHandle:a,className:t,...r})=>e(Mt.PanelResizeHandle,{className:Ki("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Z,{className:"h-2.5 w-2.5"})})}),Pm=Va.Root,Em=Va.Trigger,Tm=Va.Close,Im=Va.Portal,Mm=r.forwardRef(({className:a,...t},r)=>e(Va.Overlay,{className:Ki("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}));Mm.displayName=Va.Overlay.displayName;const Rm=g("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"}}),Lm=r.forwardRef(({side:t="right",className:r,children:n,...i},s)=>a(Im,{children:[e(Mm,{}),a(Va.Content,{ref:s,className:Ki(Rm({side:t}),r),...i,children:[n,a(Va.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Lm.displayName=Va.Content.displayName;const zm=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Ki("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(us,{className:"mt-2"})]});zm.displayName="SheetHeader";const Fm=({className:a,...t})=>e("div",{className:Ki("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Fm.displayName="SheetBody";const Um=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{className:"mb-4"}),e("div",{className:Ki("flex flex-row justify-end gap-2",t),...n,children:r})]});Um.displayName="SheetFooter";const jm=r.forwardRef(({className:a,...t},r)=>e(Va.Title,{ref:r,className:Ki("text-lg font-semibold text-foreground",a),...t}));jm.displayName=Va.Title.displayName;const Om=r.forwardRef(({className:a,...t},r)=>e(Va.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Om.displayName=Va.Description.displayName;const Bm="sidebar:state",$m=r.createContext(null);function Vm(){const e=r.useContext($m);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const qm=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:s,children:o,...l},c)=>{const d=Ol(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Bm);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(Bm,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 x=f?"expanded":"collapsed",b=r.useMemo(()=>({state:x,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[x,f,g,d,u,m,v]);return e($m.Provider,{value:b,children:e(_o,{delayDuration:0,children:e("div",{className:Ki("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",...s},ref:c,...l,children:o})})})});qm.displayName="SidebarProvider";const Wm=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:s,...o},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=Vm();return"none"===n?e("div",{className:Ki("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...o,children:s}):c?e(Pm,{open:u,onOpenChange:m,...o,children:a(Lm,{"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(jm,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:s})]})}):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:Ki("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:Ki("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),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:s})})]})});Wm.displayName="Sidebar";const Hm=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:s}=Vm();return a(es,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Ki("h-7 w-7",t),onClick:e=>{r?.(e),s()},...n,children:[e(na,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Hm.displayName="SidebarTrigger";const Gm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Vm();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Ki("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})});Gm.displayName="SidebarRail";const Ym=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:Ki("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}));Ym.displayName="SidebarInset";const Km=r.forwardRef(({className:a,...t},r)=>e(ts,{ref:r,"data-sidebar":"input",className:Ki("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));Km.displayName="SidebarInput";const Qm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:Ki("flex flex-col gap-2 p-2",a),...t}));Qm.displayName="SidebarHeader";const Xm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Ki("flex flex-col gap-2 p-2",a),...t}));Xm.displayName="SidebarFooter";const Jm=r.forwardRef(({className:a,...t},r)=>e(us,{ref:r,"data-sidebar":"separator",className:Ki("mx-2 w-auto bg-sidebar-border",a),...t}));Jm.displayName="SidebarSeparator";const Zm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:Ki("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));Zm.displayName="SidebarContent";const eh=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:Ki("relative flex w-full min-w-0 flex-col p-2",a),...t}));eh.displayName="SidebarGroup";const ah=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?f:"div",{ref:n,"data-sidebar":"group-label",className:Ki("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}));ah.displayName="SidebarGroupLabel";const th=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?f:"button",{ref:n,"data-sidebar":"group-action",className:Ki("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}));th.displayName="SidebarGroupAction";const rh=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Ki("w-full text-sm",a),...t}));rh.displayName="SidebarGroupContent";const nh=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Ki("flex w-full min-w-0 flex-col gap-1",a),...t}));nh.displayName="SidebarMenu";const ih=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Ki("group/menu-item relative",a),...t}));ih.displayName="SidebarMenuItem";const sh=g("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"}}),oh=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:s,className:o,...l},c)=>{const d=t?f:"button",{isMobile:u,state:m}=Vm(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Ki(sh({variant:n,size:i}),o),...l});return s?("string"==typeof s&&(s={children:s}),a(So,{children:[e(Ao,{asChild:!0,children:h}),e(Do,{side:"right",align:"center",hidden:"collapsed"!==m||u,...s})]})):h});oh.displayName="SidebarMenuButton";const lh=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?f:"button",{ref:i,"data-sidebar":"menu-action",className:Ki("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}));lh.displayName="SidebarMenuAction";const ch=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Ki("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}));ch.displayName="SidebarMenuBadge";const dh=r.forwardRef(({className:t,showIcon:n=!1,...i},s)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:s,"data-sidebar":"menu-skeleton",className:Ki("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":o}})]})});dh.displayName="SidebarMenuSkeleton";const uh=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Ki("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}));uh.displayName="SidebarMenuSub";const mh=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));mh.displayName="SidebarMenuSubItem";const hh=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},s)=>e(a?f:"a",{ref:s,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Ki("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}));hh.displayName="SidebarMenuSubButton";const ph=r.forwardRef(({className:t,value:r,defaultValue:n,...i},s)=>{const o=r||n||[0];return a(Rt.Root,{ref:s,value:r,defaultValue:n,className:Ki("relative flex w-full touch-none select-none items-center",t),...i,children:[e(Rt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Rt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(Rt.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 fh({children:a,className:t}){return e("div",{className:Ki("flex flex-col h-full",t),children:e(Ho,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function gh({title:t,description:r,actions:n,className:i}){return a("div",{className:Ki("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(us,{})]})}function vh({children:a,className:t}){return e("div",{className:Ki("space-y-6",t),children:a})}ph.displayName=Rt.Root.displayName;const xh=Lt.Menu,bh=Lt.Group,yh=Lt.Portal,Nh=Lt.Sub,wh=Lt.RadioGroup,Ch=r.forwardRef(({className:a,...t},r)=>e(Lt.Root,{ref:r,className:Ki("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Ch.displayName=Lt.Root.displayName;const kh=r.forwardRef(({className:a,...t},r)=>e(Lt.Trigger,{ref:r,className:Ki("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}));kh.displayName=Lt.Trigger.displayName;const _h=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(Lt.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));_h.displayName=Lt.SubTrigger.displayName;const Sh=r.forwardRef(({className:a,...t},r)=>e(Lt.SubContent,{ref:r,className:Ki("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}));Sh.displayName=Lt.SubContent.displayName;const Ah=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},s)=>e(Lt.Portal,{children:e(Lt.Content,{ref:s,align:t,alignOffset:r,sideOffset:n,className:Ki("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})}));Ah.displayName=Lt.Content.displayName;const Dh=r.forwardRef(({className:a,inset:t,...r},n)=>e(Lt.Item,{ref:n,className:Ki("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}));Dh.displayName=Lt.Item.displayName;const Ph=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(Lt.CheckboxItem,{ref:s,className:Ki("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(Lt.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),r]}));Ph.displayName=Lt.CheckboxItem.displayName;const Eh=r.forwardRef(({className:t,children:r,...n},i)=>a(Lt.RadioItem,{ref:i,className:Ki("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(Lt.ItemIndicator,{children:e(F,{className:"h-2 w-2 fill-current"})})}),r]}));Eh.displayName=Lt.RadioItem.displayName;const Th=r.forwardRef(({className:a,inset:t,...r},n)=>e(Lt.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Th.displayName=Lt.Label.displayName;const Ih=r.forwardRef(({className:a,...t},r)=>e(Lt.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));Ih.displayName=Lt.Separator.displayName;const Mh=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Mh.displayname="MenubarShortcut";const Rh={light:"",dark:".dark"},Lh=r.createContext(null);function zh(){const e=r.useContext(Lh);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Fh=r.forwardRef(({id:t,className:n,children:i,config:s,...o},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Lh.Provider,{value:{config:s},children:a("div",{"data-chart":d,ref:l,className:Ki("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Uh,{id:d,config:s}),e(zt.ResponsiveContainer,{children:i})]})})});Fh.displayName="Chart";const Uh=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Rh).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},jh=zt.Tooltip,Oh=r.forwardRef(({active:n,payload:i,className:s,indicator:o="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:x}=zh(),b=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=Vh(x,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:x[d]?.label||d;return u?e("div",{className:Ki("font-medium",m),children:u(r,i)}):r?e("div",{className:Ki("font-medium",m),children:r}):null},[d,u,i,l,m,x,g]);if(!n||!i?.length)return null;const y=1===i.length&&"dot"!==o;return a("div",{ref:v,className:Ki("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",s),children:[y?null:b,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,s=Vh(x,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:Ki("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[s?.icon?e(s.icon,{}):!c&&e("div",{className:Ki("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":y&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:Ki("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[y?b:null,e("span",{className:"text-muted-foreground",children:s?.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)})})]})});Oh.displayName="ChartTooltip";const Bh=zt.Legend,$h=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:s},o)=>{const{config:l}=zh();return n?.length?e("div",{ref:o,className:Ki("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${s||t.dataKey||"value"}`,i=Vh(l,t,n);return a("div",{className:Ki("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 Vh(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]}$h.displayName="ChartLegend";const qh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:Ki("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}),Wh=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Hh=({value:t,onChange:n,disabled:s,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=Zt({extensions:[ar.configure({heading:{levels:[1,2,3]}}),tr,rr.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),nr,ir,sr.configure({multicolor:!0})],content:t||"",editable:!s,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=o(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:Ki("space-y-2",m),children:[d&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(es,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:s,children:[e(ia,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(es,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:s,children:[e(sa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(es,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:s,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(qh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:s,title:"Título 1",children:e(oa,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:s,title:"Título 2",children:e(la,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:s,title:"Título 3",children:e(ca,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:s,title:"Negrito",children:e(da,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:s,title:"Itálico",children:e(ua,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:s,title:"Sublinhado",children:e(ma,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:s,title:"Riscado",children:e(ha,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:s,title:"Lista",children:e(Q,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:s,title:"Lista Ordenada",children:e(pa,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:s,title:"Destacar",children:e(fa,{className:"h-4 w-4"})}),e(qh,{onClick:g,isActive:f.isActive("link"),disabled:s,title:"Link",children:e(ga,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:s,title:"Limpar Formatação",children:e(va,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().undo().run(),disabled:s||!f.can().undo(),title:"Desfazer",children:e(xa,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().redo().run(),disabled:s||!f.can().redo(),title:"Refazer",children:e(ba,{className:"h-4 w-4"})})]}),e(er,{editor:f,className:Ki("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:s,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 Gh({image:a,title:t,className:r}){return e("div",{className:Ki("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(ya,{className:"w-16 h-16 text-muted-foreground"})})})}function Yh({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:s}){const o=t.length,l=(r+1)/o*100;return a("div",{className:Ki("flex items-center gap-3",s),children:[a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",o,e(A,{className:"h-3 w-3 ml-1"})]})}),e(xo,{align:"start",children:t.map((e,t)=>a(bo,{onClick:()=>n(t),className:Ki(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Cm,{value:l,className:"w-32 h-2"})]})}function Kh({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:s,backButtonText:o,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:Ki("flex items-center gap-2",d),children:[!u&&a(es,{variant:"outline",onClick:n,size:"sm",children:[e(Pe,{className:"h-4 w-4 mr-2"}),o]}),a(es,{onClick:m?s:i,size:"sm",children:[m?c:l,!m&&e(De,{className:"h-4 w-4 ml-2"})]})]})}const Qh=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:s,onStepChange:o,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[x,b]=r.useState(0),y=void 0!==p,N=y?p:x,w=r.useCallback(e=>{y?f?.(e):b(e),o?.(e)},[y,f,o]);r.useEffect(()=>{t||y||b(0)},[t,y]);const C=i[N],k=i.length;return C?e(Cs,{open:t,onOpenChange:n,children:a(Ps,{ref:v,size:m,variant:"informative",className:Ki("p-0 gap-0 overflow-hidden",g),children:[a(Ss,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Gh,{image:C.image,title:C.title}),e(Ms,{className:"text-xl font-semibold",children:C.title}),e(Rs,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(us,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(Yh,{steps:i,currentStepIndex:N,onStepSelect:e=>{w(e)},stepLabel:u}):e("div",{}),e(Kh,{currentStepIndex:N,totalSteps:k,onBack:()=>{N>0&&w(N-1)},onNext:()=>{N<k-1&&w(N+1)},onComplete:()=>{s?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function Xh({label:t,onClick:r,icon:n,actions:i=[],variant:s="default",size:o="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(es,{variant:s,size:o,disabled:m,onClick:r,className:u,children:[c?e(E,{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:Ki("inline-flex rounded-md shadow-sm",u),children:[a(es,{variant:s,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:s,size:o,disabled:m,className:Ki("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(A,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(xo,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(bo,{onClick:t.onClick,disabled:t.disabled,className:Ki("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}var Jh,Zh;Qh.displayName="OnboardingDialog",(Zh=Jh||(Jh={})).CSV="csv",Zh.PDF="pdf",Zh.XLSX="xlsx",Zh.PNG="png",Zh.JPEG="jpeg",Zh.SVG="svg";const ep=[{value:Jh.CSV,label:"CSV",icon:e(xe,{className:"h-5 w-5"})},{value:Jh.PDF,label:"PDF",icon:e(xe,{className:"h-5 w-5"})},{value:Jh.XLSX,label:"XLSX",icon:e(Na,{className:"h-5 w-5"})}],ap=[{value:Jh.PNG,label:"PNG",icon:e(Fe,{className:"h-5 w-5"})},{value:Jh.JPEG,label:"JPEG",icon:e(wa,{className:"h-5 w-5"})},{value:Jh.SVG,label:"SVG",icon:e(wa,{className:"h-5 w-5"})},{value:Jh.PDF,label:"PDF",icon:e(xe,{className:"h-5 w-5"})}];function tp({open:t,onOpenChange:r,onExport:n,mode:s="table",options:o,title:l,description:c,cancelLabel:d="Cancelar",exportLabel:u="Exportar"}){const[m,h]=i(""),p=o??("chart"===s?ap:ep),f=c??"Selecione o formato do arquivo",g=e=>{e||h(""),r(e)};return e(Cs,{open:t,onOpenChange:g,children:a(Ps,{className:"sm:max-w-md",children:[e(Es,{children:e(Ms,{children:l??("chart"===s?"Exportar gráfico":"Exportar tabela")})}),a("div",{className:"py-4",children:[e("p",{className:"text-sm text-muted-foreground mb-4",children:f}),e(km,{value:m,onValueChange:h,className:"gap-3",children:p.map(t=>a("div",{className:"flex items-center space-x-3",children:[e(_m,{value:t.value,id:`export-${t.value}`}),a(ns,{htmlFor:`export-${t.value}`,className:Ki("flex items-center gap-2 cursor-pointer font-normal",m===t.value&&"font-medium"),children:[t.icon,t.label]})]},t.value))})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>g(!1),children:d}),e(es,{onClick:()=>{m&&(n(m),r(!1),h(""))},disabled:!m,children:u})]})]})})}const rp=p(({value:t,onChange:n,onTimeChange:i,label:s,error:l,format:c="24h",className:d,id:u,...m},h)=>{const p=u??r.useId(),f=o(e=>{const a=e.target.value;n?.(a),i?.(a)},[n,i]),g=o(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return a("div",{className:Ki("grid gap-1.5",d),children:[s&&e(ns,{htmlFor:p,children:s}),a("div",{className:"relative",children:[e(ts,{ref:h,id:p,type:"time",value:t??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Ki("pr-9",l&&"border-destructive focus-visible:ring-destructive"),...m}),e(Ae,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),l&&e("p",{className:"text-sm text-destructive",children:l})]})});function np({open:t,onOpenChange:r,onConfirm:n,onGenerateCode:s,mode:l="code",email:c,maxLength:d=8,title:u="Assinatura Eletrônica",description:m,confirmLabel:h="Confirmar",cancelLabel:p="Cancelar",resendLabel:f="Reenviar código",errorMessage:g}){const v="password"===l,x=m??(v?"Digite sua senha para confirmar a operação.":"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação."),[b,y]=i(""),[N,w]=i(!1),[C,k]=i(!1),[_,S]=i(null),A=o(async()=>{if(b.trim()){w(!0),S(null);try{await n(b)?(y(""),r(!1)):S(g??(v?"Senha incorreta. Tente novamente.":"Código inválido. Tente novamente."))}catch{S(g??(v?"Erro ao validar a senha. Tente novamente.":"Erro ao validar o código. Tente novamente."))}finally{w(!1)}}},[b,n,r,g,v]),D=o(async()=>{if(s){k(!0),S(null);try{await s()}catch{S("Erro ao reenviar o código.")}finally{k(!1)}}},[s]),P=e=>{e||(y(""),S(null)),r(e)},E=v?"Senha":"Código de verificação",T=v?"Digite sua senha":"Digite o código";return e(Cs,{open:t,onOpenChange:P,children:a(Ps,{className:"sm:max-w-md",children:[e(Es,{children:a(Ms,{className:"flex items-center gap-2",children:[e(v?pe:Ca,{className:"h-5 w-5 text-primary"}),u]})}),a("div",{className:"py-4 space-y-4",children:[e("p",{className:"text-sm text-muted-foreground",children:x}),!v&&c&&a("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[e($e,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-muted-foreground",children:"Enviado para:"}),e("span",{className:"font-medium",children:c})]}),a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"signature-input",children:E}),e(ts,{id:"signature-input",type:v?"password":"text",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"===e.key&&b.trim()&&(e.preventDefault(),A())},maxLength:v?void 0:d,placeholder:T,autoFocus:!0,className:Ki(_&&"border-destructive focus-visible:ring-destructive")}),_&&e("p",{className:"text-sm text-destructive",children:_})]}),!v&&a(es,{variant:"ghost",size:"sm",onClick:D,disabled:C,className:"text-primary",children:[e(Je,{className:Ki("h-4 w-4 mr-1",C&&"animate-spin")}),f]})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>P(!1),disabled:N,children:p}),e(es,{onClick:A,disabled:!b.trim()||N,children:N?"Validando...":h})]})]})})}function ip({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:s,className:o,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!s&&!s(e));return a("div",{className:Ki("flex items-center gap-3",o),children:[a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(A,{className:"h-3 w-3 ml-1"})]})}),e(xo,{align:"start",children:c.map(r=>a(bo,{onClick:()=>{var e;(e=r)<t?n(e):s&&!s(e)||n(e)},disabled:d(r),className:Ki("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(P,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Cm,{value:t/r*100,className:Ki("h-2",l)})]})}function sp(e){const a=cl.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 op(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await xl.handleApiError({status:401})){const n={...a,headers:sp(t)};r=await fetch(e,n)}}return r}function lp(e){const[a,t]=i([]),[r,n]=i(0),[s,l]=i(!1);u(()=>{if(!e)return;let a=!1;const r=`${Pr().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){l(!0);try{const i=sp(e),s=await op(r,{method:"GET",headers:i},e);if(!s.ok)return;const o=await s.json();!a&&o.data?.[0]&&(t(o.data[0].updates??[]),n(o.data[0].valueBadge??0))}catch(i){}finally{a||l(!1)}}(),()=>{a=!0}},[e]);const c=o(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${Pr().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=sp(e),r=JSON.stringify({id:t,idUpdateType:3});await op(i,{method:"POST",headers:a,body:r},e)}catch(s){}},[e,r,a]);return{updates:a,badgeCount:r,loading:s,markAsVisualized:c}}rp.displayName="Timepicker";const cp=n.forwardRef(({updates:t,badgeCount:r,onOpen:n,onViewAll:i},s)=>{const o=void 0===t,l=zl(),c=l?.alias??null,d=lp(o?c:null),u=o?d.updates??[]:t,m=o?d.badgeCount??0:r??0,h=n??(o?d.markAsVisualized:void 0),p=i??(o&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return a(Eo,{children:[e(To,{asChild:!0,children:a(es,{ref:s,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(ka,{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(Io,{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(ka,{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(es,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e(De,{className:"h-[18px] w-[18px]"})]})})]})]})});var dp,up,mp,hp;cp.displayName="UpdatesNotification",(up=dp||(dp={}))[up.none=0]="none",up[up.image=1]="image",up[up.video=2]="video",up[up.audio=3]="audio",up[up.wopi=4]="wopi",up[up.onlineEditor=5]="onlineEditor",up[up.report=6]="report",(hp=mp||(mp={}))[hp.SimplePrint=0]="SimplePrint",hp[hp.ManagedCopy=1]="ManagedCopy",hp[hp.NonManagedCopy=2]="NonManagedCopy";const pp={".jpg":dp.image,".jpeg":dp.image,".png":dp.image,".bmp":dp.image,".gif":dp.image,".svg":dp.image,".webp":dp.image,".wav":dp.audio,".mp3":dp.audio,".mp4":dp.video,".webm":dp.video,".ogg":dp.video,".pdf":dp.wopi,".ods":dp.wopi,".xls":dp.wopi,".xlsb":dp.wopi,".xlsm":dp.wopi,".xlsx":dp.wopi,".doc":dp.wopi,".docm":dp.wopi,".docx":dp.wopi,".dot":dp.wopi,".dotm":dp.wopi,".dotx":dp.wopi,".odt":dp.wopi,".odp":dp.wopi,".pot":dp.wopi,".potm":dp.wopi,".potx":dp.wopi,".pps":dp.wopi,".ppsm":dp.wopi,".ppsx":dp.wopi,".ppt":dp.wopi,".pptm":dp.wopi,".pptx":dp.wopi,".gdocs":dp.onlineEditor,".gsheets":dp.onlineEditor};function fp(e){return e?pp[e.toLowerCase()]??dp.none:dp.none}function gp(e){return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const vp={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function xp(e){return vp[e?.toLowerCase()]||""}function bp(e){const{viewerUrl:a,wopiUrl:t,fileId:r,token:n,extension:i,language:s="pt-br"}=e,o=xp(i);if(!o)return null;return`${a}${o}ui=${s}&rs=${s}&access_token=${n}&WOPISrc=${encodeURIComponent(`${t}${r}`)}`}function yp({open:r,onOpenChange:n,template:i,viewerType:s,isLoading:l=!1,enableDownload:c=!0,onDownload:m,isDownloading:h=!1,enableFavorite:p=!1,isFavorite:f=!1,onFavorite:g,isFavoriting:v=!1,enableConfirmReading:x=!1,readingConfirmationDate:b,onConfirmReading:y,isConfirmingReading:N=!1,readingConfirmationTimeRemaining:w,onIframeLoad:C,className:k}){const _=d(null),A=s??fp(i.extension),D=h||N||v,P=i.code?`${i.code} – ${i.name}`:i.name,E=o(()=>{_.current&&C&&C(_.current)},[C]);return u(()=>{if(!r)return;const e=e=>{"Escape"===e.key&&n(!1)};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[r,n]),e(Cs,{open:r,onOpenChange:n,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(A===dp.wopi||A===dp.report)&&"w-[90vw]",k),children:[a("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[e("h2",l?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:P}),a("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!l&&a(t,{children:[(x||b)&&e(t,{children:b?a("div",{className:"flex flex-col mr-2.5",children:[a("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[e(_a,{className:"h-4 w-4"}),"Leitura confirmada"]}),e("span",{className:"text-xs text-muted-foreground ml-5",children:b.toLocaleDateString()})]}):null!=w&&w>0?a("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[e("span",{children:"Confirmação disponível em"}),e("span",{className:"font-medium min-w-[72px]",children:Np(w)}),e("span",{children:"segundos"})]}):a(es,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[e(Ca,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":"Confirmar leitura"]})}),A!==dp.none&&p&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:e(Ge,{className:Ki("h-4 w-4",f&&"fill-accent text-accent")})})}),e(Do,{children:f?"Desfavoritar":"Favoritar"})]}),A!==dp.none&&c&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>m?.(),children:e(Ce,{className:"h-4 w-4"})})}),e(Do,{children:"Download"})]})]}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})]})]}),e("div",{className:Ki("flex flex-col items-center justify-center min-h-[160px] w-full",l&&"relative -top-5",A===dp.none&&"min-h-[124px]",A===dp.image&&"max-h-[85vh]",(A===dp.wopi||A===dp.report)&&"min-w-[77vw] min-h-[80vh]"),children:l?e(so,{className:"h-14 w-14"}):a(t,{children:[(A===dp.none||!i.url)&&a("div",{className:"text-center",children:[e("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),e("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),A===dp.image&&e("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),A===dp.video&&e("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),A===dp.audio&&e("audio",{controls:!0,autoPlay:!0,src:i.url}),(A===dp.wopi||A===dp.report)&&a("div",{className:"relative w-full h-[79.5vh]",children:[e(so,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e("iframe",{ref:_,src:i.url,onLoad:E,className:"border-none w-full h-full z-[1] relative",title:i.name})]})]})}),!l&&A===dp.none&&a("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[e(es,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),c&&e(es,{variant:"default",onClick:()=>m?.(),children:"Download"})]})]})})}function Np(e){const a=e%60;return`${Math.floor(e/60)}min ${a<10?"0":""}${a}`}function wp({open:t,onOpenChange:r,identifier:n,fileName:s,mode:l="edit",type:c="document",onClose:d,className:m}){const[h,p]=i(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,l,c);u(()=>{if(t){p(!0);const e=setTimeout(()=>p(!1),300);return()=>clearTimeout(e)}},[t]);const g=o(()=>{d?.(),r(!1)},[d,r]);return u(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&g()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[t,g]),e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",m),children:[a("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[e("h2",h?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:s}),e("div",{className:"flex items-center ml-4 z-20",children:a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})})]}),e("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:h?e(so,{className:"h-14 w-14"}):a("div",{className:"relative w-full h-[79.5vh]",children:[e(so,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e("iframe",{src:f,className:"border-none w-full h-full z-[1] relative",title:s})]})})]})})}function Cp({open:t,onOpenChange:r,url:n,title:i,className:s,minHeight:l="250px"}){const c=o(()=>{r(!1)},[r]);return u(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&c()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[t,c]),e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",s),children:[a("div",{className:"flex items-center justify-end mb-2.5",children:[i&&e("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:i}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})]}),e("iframe",{src:n,className:"border-none w-full",style:{minHeight:l},title:i||"Embedded content"})]})})}function kp({term:r,open:n,onClose:s,onAgree:l,title:c="Termos de Uso Atualizados",seeLaterLabel:d="Ver depois",agreeLabel:u="Li e concordo",viewTermLabel:m="Visualizar termo de uso"}){const[h,p]=i(!1),f=o(()=>{l(r.id)},[l,r.id]);return a(t,{children:[e(Cs,{open:n&&!h,onOpenChange:e=>!e&&s(),children:a(Ps,{className:"sm:max-w-md",children:[e(Es,{children:a(Ms,{className:"flex items-center gap-2",children:[e(Ca,{className:"h-5 w-5 text-primary"}),c]})}),a("div",{className:"space-y-4",children:[r.description&&e(Ho,{className:"max-h-48",children:e("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:r.description}})}),r.file&&a(es,{variant:"link",className:"px-0 text-primary",onClick:()=>p(!0),children:[e(Ze,{className:"mr-1 h-4 w-4"}),m]})]}),a(Is,{className:"gap-2 sm:gap-0",children:[e(es,{variant:"ghost",onClick:s,children:d}),e(es,{onClick:f,children:u})]})]})}),h&&e(_p,{term:r,open:h,onClose:()=>p(!1),viewOnly:!0})]})}function _p({term:t,open:r,onClose:n,onSign:i,viewOnly:l=!1,title:c="Termos de Uso",signLabel:d="Li e concordo"}){const u=s(()=>t.file?function(e,a=""){const t=atob(e),r=[];for(let i=0;i<t.length;i+=512){const e=t.slice(i,i+512),a=new Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t);r.push(new Uint8Array(a))}const n=new Blob(r,{type:a});return URL.createObjectURL(n)}(t.file,t.type):null,[t.file,t.type]),m=o(()=>{u&&URL.revokeObjectURL(u),n()},[u,n]),h=o(()=>{t.hasUserSignature?m():i?.(t.id)},[t,i,m]),p=!l&&!t.hasUserSignature&&i;return e(Cs,{open:r,onOpenChange:e=>!e&&m(),children:a(Ps,{className:Ki("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[a("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[a("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e(xe,{className:"h-5 w-5 text-primary"}),c]}),a("div",{className:"flex items-center gap-2",children:[p&&e(es,{size:"sm",onClick:h,children:d}),e(es,{variant:"ghost",size:"icon",onClick:m,children:e(S,{className:"h-4 w-4"})})]})]}),e("div",{className:"flex-1 min-h-0",children:t.file&&u?e("iframe",{className:"h-full w-full border-0",src:u,title:c}):e("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:e("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function Sp(e){return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function Ap(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Dp({users:t,groups:r=[],value:n,onChange:l,disabled:c=!1,maxHeight:d=350,hideGroupFilter:u=!1,searchPlaceholder:m="Buscar usuário...",selectLabel:h="Selecionar",doneLabel:p="Concluir",allLabel:f="Todos",emptyLabel:g="Nenhum usuário selecionado",selectedLabel:v="selecionado",selectedPluralLabel:x="selecionados",className:b}){const[y,N]=i(!1),[w,C]=i(""),[k,_]=i(void 0),S=s(()=>new Set(n),[n]),A=s(()=>{let e=t;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),w){const a=Ap(w);e=e.filter(e=>Ap(e.name).includes(a)||Ap(e.email??"").includes(a))}return e},[t,k,w]),D=s(()=>y?A:t.filter(e=>S.has(e.id)),[y,A,t,S]),P=n.length,E=s(()=>A.length>0&&A.every(e=>S.has(e.id)),[A,S]),T=o(e=>{if(c)return;const a=S.has(e)?n.filter(a=>a!==e):[...n,e];l(a)},[n,S,l,c]),I=o(e=>{if(c)return;const a=new Set(A.map(e=>e.id));if(e){const e=new Set([...n,...a]);l(Array.from(e))}else l(n.filter(e=>!a.has(e)))},[n,A,l,c]),M=o(()=>{N(e=>!e),C(""),_(void 0)},[]);return a("div",{className:Ki("rounded-md border bg-muted/30",b),children:[(!c||P>0)&&a("div",{className:Ki("flex items-center justify-between px-4 py-2",!c&&"cursor-pointer hover:bg-muted/50"),onClick:c?void 0:M,children:[e("span",{className:"text-sm font-medium text-primary uppercase",children:!c&&(y?p:h)}),e("span",{className:"text-xs text-muted-foreground",children:P>0&&`${P} ${1===P?v:x}`})]}),a("div",{className:"px-4 pb-3",children:[y&&a("div",{className:"flex gap-3 mb-3",children:[!u&&r.length>0&&a(Ws,{value:k??"__all__",onValueChange:e=>_("__all__"===e?void 0:e),children:[e(Ys,{className:"w-[200px] h-9 text-sm",children:e(Gs,{placeholder:"Grupo de usuários"})}),a(Xs,{children:[e(Zs,{value:"__all__",children:"Todos os grupos"}),r.map(a=>e(Zs,{value:a.id,children:a.name},a.id))]})]}),a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-9 text-sm",placeholder:m,value:w,onChange:e=>C(e.target.value)})]})]}),!y&&0===P&&a("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[e(Sa,{className:"h-4 w-4 mr-2"}),g]}),y&&A.length>0&&a("div",{className:"flex items-center gap-2 mb-2",children:[e(ao,{checked:E,onCheckedChange:e=>I(!!e)}),e("span",{className:"text-sm",children:f})]}),D.length>0&&e(Ho,{style:{maxHeight:d},className:"pr-2",children:e("div",{className:"space-y-0.5",children:D.map(t=>a("div",{className:Ki("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",y&&!c&&"cursor-pointer hover:bg-accent/50"),onClick:y?()=>T(t.id):void 0,children:[y&&e(ao,{checked:S.has(t.id),onCheckedChange:()=>T(t.id),onClick:e=>e.stopPropagation()}),a(cu,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e(du,{src:t.avatar,alt:t.name}),e(uu,{className:"text-xs",children:Sp(t.name)})]}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"font-normal truncate",children:t.name}),t.email&&e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})}),y&&0===A.length&&e("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})}function Pp(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Ep(e){const a=new Set;if(!e)return a;for(const t of e)t.allowedIds?.forEach(e=>a.add(e)),t.inheritedIds?.forEach(e=>a.add(e));return a}function Tp({items:t,categories:r,value:n,onChange:l,readonly:c=!1,isLoading:d=!1,title:u="Permissões",addButtonLabel:m="Permitir",chipsTitle:h="Itens permitidos",chipsPlaceholder:p="Nenhum item selecionado",searchPlaceholder:f="Buscar...",selectPlaceholder:g="Selecione itens para adicionar...",itemInfoTemplate:v=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:x,disclaimerLink:b,onDisclaimerClick:y,className:N}){const[w,C]=i(r[0]?.id??""),[k,_]=i(""),[D,E]=i([]),[T,I]=i(!1),M=s(()=>Ep(n[w]),[n,w]),R=s(()=>function(e){const a=new Set;if(!e)return a;for(const t of e)t.inheritedIds?.forEach(e=>a.add(e));return a}(n[w]),[n,w]),L=s(()=>t.filter(e=>M.has(e.id)),[t,M]),z=s(()=>{const e=Pp(k);return t.filter(a=>!M.has(a.id)&&!(e&&!Pp(a.name).includes(e)))},[t,M,k]),F=s(()=>{const e={};for(const a of r)e[a.id]=Ep(n[a.id]).size;return e},[r,n]),U=o(e=>{C(e),E([]),_("")},[]),O=o(e=>{E(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),B=o(()=>{if(0===D.length)return;const e=[...n[w]??[]];for(const a of D){const r=t.find(e=>e.id===a),n=r?.group??"default",i=e.find(e=>e.context===n);i?i.allowedIds.includes(a)||(i.allowedIds=[...i.allowedIds,a]):e.push({context:n,allowedIds:[a],inheritedIds:[]})}l({...n,[w]:e}),E([]),_(""),I(!1)},[D,n,w,t,l]),$=o(e=>{if(R.has(e))return;const a=(n[w]??[]).map(a=>({...a,allowedIds:a.allowedIds.filter(a=>a!==e)}));l({...n,[w]:a})},[n,w,R,l]);return d?a("div",{className:Ki("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",N),children:[e("div",{className:"h-4 w-32 bg-muted rounded"}),e("div",{className:"h-9 w-full bg-muted rounded"}),e("div",{className:"h-20 w-full bg-muted rounded"})]}):e("div",{className:Ki("rounded-md border bg-muted/30",N),children:a("div",{className:"p-4 space-y-4",children:[a("div",{className:"space-y-2",children:[e("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:u}),a(Ws,{value:w,onValueChange:U,children:[e(Ys,{className:"h-9 text-sm",children:e(Gs,{})}),e(Xs,{children:r.map(t=>e(Zs,{value:t.id,children:a("span",{className:"flex items-center gap-2",children:[t.icon,t.name,F[t.id]>0&&e(no,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:F[t.id]})]})},t.id))})]})]}),!c&&a("div",{className:"flex gap-2",children:[a(Eo,{open:T,onOpenChange:I,children:[e(To,{asChild:!0,children:a(es,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[D.length>0?`${D.length} selecionado${D.length>1?"s":""}`:g,e(A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),a(Io,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[e("div",{className:"p-2 border-b",children:a("div",{className:"relative",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-8 text-sm",placeholder:f,value:k,onChange:e=>_(e.target.value)})]})}),e(Ho,{className:"max-h-[220px]",children:0===z.length?e("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):e("div",{className:"p-1",children:z.map(t=>{const r=D.includes(t.id);return a("div",{className:Ki("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>O(t.id),children:[e("div",{className:Ki("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&e(P,{className:"h-3 w-3"})}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"truncate",children:t.name}),null!=t.count&&e("span",{className:"text-xs text-muted-foreground",children:v(t.count)})]})]},t.id)})})})]})]}),a(es,{size:"sm",className:"h-9 gap-1",disabled:0===D.length,onClick:B,children:[e(Y,{className:"h-4 w-4"}),m]})]}),a("div",{className:"space-y-2",children:[e("p",{className:"text-sm font-medium",children:h}),e("div",{className:Ki("rounded-md border bg-background p-3 min-h-[60px]",c&&"bg-muted/50"),children:0===L.length?e("span",{className:"text-sm text-muted-foreground",children:p}):e("div",{className:"flex flex-wrap gap-1.5",children:L.map(t=>{const r=R.has(t.id);return a(no,{variant:r?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[t.name,!c&&!r&&e("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>$(t.id),children:e(S,{className:"h-3 w-3"})})]},t.id)})})}),c&&x&&a("p",{className:"text-xs text-muted-foreground",children:[e("span",{dangerouslySetInnerHTML:{__html:x}})," ",b&&y&&e("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:y,children:b})]})]})]})})}var Ip,Mp;(Mp=Ip||(Ip={}))[Mp.WaitingProcessing=1]="WaitingProcessing",Mp[Mp.Processing=2]="Processing",Mp[Mp.Completed=3]="Completed",Mp[Mp.Error=4]="Error",Mp[Mp.Expired=5]="Expired";const Rp={report:"Relatório",status:"Status",requestDate:"Data da solicitação",lastUpdate:"Última atualização",expirationDate:"Data de expiração",viewReport:"Visualizar relatório",searchPlaceholder:"Buscar relatório...",noResults:"Nenhum relatório encontrado",statusWaiting:"Aguardando",statusProcessing:"Processando",statusCompleted:"Concluído",statusError:"Erro",statusExpired:"Expirado"};function Lp(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function zp(e){return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Fp({requests:r,isLoading:n=!1,onGetReportUrl:l,formatDate:c=zp,labels:d,className:u}){const m={...Rp,...d},[h,p]=i(""),[f,g]=i(!1),[v,x]=i(""),[b,y]=i(""),[N,w]=i(null),C=s(()=>{if(!h)return r;const e=Lp(h);return r.filter(a=>Lp(a.reportName).includes(e))},[r,h]),k=o(async e=>{if(!N){w(e.id);try{const a=await l(e.id);a&&(x(a),y(e.reportName),g(!0))}finally{w(null)}}},[l,N]);return n?e("div",{className:Ki("space-y-3",u),children:Array.from({length:5}).map((a,t)=>e($o,{className:"h-12 w-full"},t))}):a(t,{children:[a("div",{className:Ki("space-y-3",u),children:[a("div",{className:"relative max-w-sm",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-9 text-sm",placeholder:m.searchPlaceholder,value:h,onChange:e=>p(e.target.value)})]}),e(Ho,{className:"rounded-md border",children:a(Bl,{children:[e($l,{children:a(Wl,{children:[e(Hl,{className:"min-w-[140px]",children:m.report}),e(Hl,{className:"min-w-[150px]",children:m.status}),e(Hl,{className:"min-w-[160px]",children:m.requestDate}),e(Hl,{className:"min-w-[160px]",children:m.lastUpdate}),e(Hl,{className:"min-w-[160px]",children:m.expirationDate}),e(Hl,{className:"min-w-[140px]"})]})}),e(Vl,{children:0===C.length?e(Wl,{children:e(Gl,{colSpan:6,className:"text-center text-muted-foreground py-8",children:m.noResults})}):C.map(t=>{const r=function(e){return new Date>new Date(e.expirationDate)&&e.statusId===Ip.Completed?Ip.Expired:e.statusId}(t),n=function(a,t){switch(a){case Ip.WaitingProcessing:return{label:t.statusWaiting,icon:e(Pa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case Ip.Processing:return{label:t.statusProcessing,icon:e(Je,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case Ip.Completed:return{label:t.statusCompleted,icon:e(Da,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case Ip.Error:return{label:t.statusError,icon:e(U,{className:"h-3.5 w-3.5"}),variant:"danger"};case Ip.Expired:return{label:t.statusExpired,icon:e(Aa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(r,m),i=r===Ip.Completed,s=r===Ip.Expired;return a(Wl,{children:[e(Gl,{className:"font-medium",children:t.reportName}),e(Gl,{children:a(no,{variant:n.variant,className:Ki("gap-1",n.className),children:[n.icon,n.label]})}),e(Gl,{className:"text-sm",children:c(new Date(t.requestDate))}),e(Gl,{className:"text-sm",children:c(new Date(t.lastUpdate))}),e(Gl,{className:Ki("text-sm",s&&"text-destructive"),children:c(new Date(t.expirationDate))}),e(Gl,{children:a(es,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!i||N===t.id,onClick:()=>k(t),children:[N===t.id?e(E,{className:"h-4 w-4 animate-spin"}):e(me,{className:"h-4 w-4"}),m.viewReport]})})]},t.id)})})]})})]}),e(Cp,{open:f,onOpenChange:g,url:v,title:b})]})}function Up({reportApiUrl:a,parameters:t={},minHeight:r="80vh",...n}){const i=s(()=>{const e=`${a}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${e}?${r}`:e},[a,t]);return e(Cp,{...n,url:i,minHeight:r})}var jp,Op,Bp,$p,Vp,qp,Wp,Hp,Gp,Yp,Kp,Qp,Xp,Jp,Zp,ef,af,tf,rf,nf,sf,of,lf,cf,df,uf,mf,hf,pf,ff,gf,vf,xf,bf,yf,Nf,wf,Cf,kf,_f,Sf,Af,Df,Pf,Ef,Tf,If,Mf,Rf,Lf,zf;(Op=jp||(jp={})).Count="valuecount",Op.Sum="sum",Op.Average="average",Op.DistinctCount="valuecount_distict",Op.Max="max",Op.Min="min",(Bp||(Bp={})).ViewAllAnalysis="nes3j6wn",(Vp=$p||($p={})).RegisterDashboards="EeKs7CYA",Vp.RemoveDashboards="3GKZYOQ9",Vp.ViewAllDashboards="wYBdQNvZ",Vp.EditDashboards="bMFcbwv4",(Wp=qp||(qp={}))[Wp.Default=1]="Default",Wp[Wp.Compact=2]="Compact",(Gp=Hp||(Hp={}))[Gp.FiveSeconds=1]="FiveSeconds",Gp[Gp.TenSeconds=2]="TenSeconds",Gp[Gp.FifteenSeconds=3]="FifteenSeconds",Gp[Gp.ThirtySeconds=4]="ThirtySeconds",Gp[Gp.OneMinute=5]="OneMinute",Gp[Gp.ThreeMinutes=6]="ThreeMinutes",Gp[Gp.FiveMinutes=7]="FiveMinutes",Gp[Gp.TenMinutes=8]="TenMinutes",(Kp=Yp||(Yp={}))[Kp.Day=1]="Day",Kp[Kp.Month=2]="Month",Kp[Kp.Year=3]="Year",(Xp=Qp||(Qp={}))[Xp.Ascending=1]="Ascending",Xp[Xp.Descending=2]="Descending",(Zp=Jp||(Jp={}))[Zp.Label=1]="Label",Zp[Zp.Value=2]="Value",(af=ef||(ef={}))[af.LastSevenDays=1]="LastSevenDays",af[af.LastWeek=2]="LastWeek",af[af.LastMonth=3]="LastMonth",af[af.PreviousQuarter=4]="PreviousQuarter",af[af.PreviousSemester=5]="PreviousSemester",af[af.LastYear=6]="LastYear",af[af.SpecificPeriod=7]="SpecificPeriod",af[af.CurrentMonth=8]="CurrentMonth",af[af.CurrentSemester=9]="CurrentSemester",af[af.CurrentWeek=10]="CurrentWeek",af[af.CurrentYear=11]="CurrentYear",(rf=tf||(tf={}))[rf.Text=1]="Text",rf[rf.Area=2]="Area",rf[rf.Bar=3]="Bar",rf[rf.Column=4]="Column",rf[rf.StackedColumn=5]="StackedColumn",rf[rf.Line=6]="Line",rf[rf.List=7]="List",rf[rf.Numeric=8]="Numeric",rf[rf.Pareto=9]="Pareto",rf[rf.Pie=10]="Pie",rf[rf.RiskMatrix=11]="RiskMatrix",rf[rf.Burndown=12]="Burndown",rf[rf.PerformanceColumns=13]="PerformanceColumns",rf[rf.EvolutionLine=14]="EvolutionLine",(sf=nf||(nf={}))[sf.NotUpdate=1]="NotUpdate",sf[sf.FiveMinutes=2]="FiveMinutes",sf[sf.TenMinutes=3]="TenMinutes",sf[sf.FifteenMinutes=4]="FifteenMinutes",sf[sf.ThirtyMinutes=5]="ThirtyMinutes",sf[sf.OneHour=6]="OneHour",(lf=of||(of={}))[lf.NormalPage=1]="NormalPage",lf[lf.Carousel=2]="Carousel",(df=cf||(cf={}))[df.General=0]="General",df[df.Share=1]="Share",(mf=uf||(uf={}))[mf.NotShared=1]="NotShared",mf[mf.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",mf[mf.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(pf=hf||(hf={})).PtBr="pt-br",pf.EnUs="en",pf.EsEs="es",(gf=ff||(ff={}))[gf.Quantity=0]="Quantity",gf[gf.AllRisksList=1]="AllRisksList",(xf=vf||(vf={}))[xf.Five=5]="Five",xf[xf.Ten=10]="Ten",xf[xf.Fifteen=15]="Fifteen",xf[xf.Twenty=20]="Twenty",xf[xf.All=0]="All",xf[xf.Custom=-1]="Custom",(yf=bf||(bf={}))[yf.AlphabeticalAsc=1]="AlphabeticalAsc",yf[yf.AlphabeticalDesc=2]="AlphabeticalDesc",yf[yf.CountAsc=3]="CountAsc",yf[yf.CountDesc=4]="CountDesc",yf[yf.DateAsc=5]="DateAsc",yf[yf.DateDesc=6]="DateDesc",(wf=Nf||(Nf={}))[wf.Loading=0]="Loading",wf[wf.Loaded=1]="Loaded",wf[wf.Error=3]="Error",wf[wf.NoData=4]="NoData",wf[wf.Unavailable=5]="Unavailable",(kf=Cf||(Cf={}))[kf.Quantity=1]="Quantity",kf[kf.Percentage=2]="Percentage",kf[kf.QuantityPercentage=3]="QuantityPercentage",(Sf=_f||(_f={}))[Sf.Program=1]="Program",Sf[Sf.Project=2]="Project",Sf[Sf.Action=3]="Action",Sf[Sf.PerformanceProject=4]="PerformanceProject",Sf[Sf.PerformanceAction=5]="PerformanceAction",(Df=Af||(Af={})).OccurrenceActionPlans="xebGnSSq",Df.OccurrenceGeneral="UFws4AvH",Df.PlansActionPlans="Kux6CcVC",Df.PlansProgramProjects="UWjrp6Dw",Df.PlansIdeas="3g7vNm2w",Df.RisksGeneral="PZ4b6FhP",Df.RisksActionPlans="xZErDg57",Df.RisksAnalysis="UxsioMbH",Df.RisksIncidences="gNt5IJ2F",Df.MetrologyGeneral="4MfEPbRY",Df.MetrologyActivities="hdFM9XQW",Df.MetrologyServiceOrders="cIrVPdMv",Df.DecisionsGeneral="CopsnHDB",Df.DecisionsItems="qLFAayjx",Df.DecisionsActionPlans="RiQFpxdb",Df.FlowGeneral="AFV98JoG",Df.AuditGeneral="gON8LJPi",Df.AuditPlans="SsCNVOvr",Df.AuditPlansItems="OpPkCCFm",Df.AuditActionPlans="P1oGePhh",Df.CommonGeneral="VVfEzgMQ",Df.ActionPlans="C6Z4MgGa",Df.SuppliersEvaluations="fSCeS4mH",Df.SuppliersGeneral="8qPThkrD",Df.SuppliersEvaluationsCriteria="RiSIStdY",Df.SuppliersDocuments="Riua4jMa",Df.SuppliersMaterialsServices="UpEkatXH",Df.DocumentsGeneral="FRhhEX2J",Df.DocumentsPhysicalCopies="PZLtJ23h",Df.DocumentsObsolete="XDjbga14",Df.FmeaGeneral="aPwf4uPr",Df.FmeaActionPlans="vQ8PMrVX",(Ef=Pf||(Pf={}))[Ef.NotShared=1]="NotShared",Ef[Ef.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",Ef[Ef.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(If=Tf||(Tf={}))[If.All=1]="All",If[If.OnlyMine=2]="OnlyMine",If[If.Favorites=3]="Favorites",(Rf=Mf||(Mf={}))[Rf.Current=1]="Current",Rf[Rf.Inherent=2]="Inherent",(zf=Lf||(Lf={}))[zf.Default=1]="Default",zf[zf.Pastel=2]="Pastel",zf[zf.Vibrant=3]="Vibrant",zf[zf.Earth=4]="Earth",zf[zf.Ocean=5]="Ocean",zf[zf.Floral=6]="Floral",zf[zf.Night=7]="Night",zf[zf.Winter=8]="Winter",zf[zf.Spring=9]="Spring",zf[zf.Summer=10]="Summer",zf[zf.Fall=11]="Fall",zf[zf.Gray=12]="Gray",zf[zf.Brown=13]="Brown",zf[zf.Blue=14]="Blue",zf[zf.Yellow=15]="Yellow",zf[zf.Green=16]="Green",zf[zf.Purple=17]="Purple",zf[zf.Orange=18]="Orange",zf[zf.Pink=19]="Pink",zf[zf.Red=20]="Red";const Ff={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},Uf={advancedFilter:"analysisDashboardsListFilter"},jf=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Of=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function Bf(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return $f(e.items[0]?.keyDate)-$f(a.items[0]?.keyDate)})}function $f(e){if(!e)return 0;const[a,t]=e.split("/"),r=Ff[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function Vf(e){return null==e?.value||""===e.value.trim()}function qf(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function Wf(e){for(const a of Of)if(e[a])return e[a];return null}function Hf(e){return e?Gf(e).join("&"):null}function Gf(e){const a=[];for(const t of Object.keys(e)){const r=e[t];null!=r&&(r instanceof Date?a.push(`${t}=${r.toISOString()}`):Array.isArray(r)?r.forEach(e=>{a.push(...Gf({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const Yf=/^-?\d+(,\d{3})*(\.\d+)?$/;function Kf(e){return!!Yf.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function Qf(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const Xf=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function Jf(e){e.forEach(a=>{a.children=e.filter(e=>e.parentId===a.id)});const a=e.filter(e=>!e.parentId);return function e(a,t){a?.forEach(a=>{t(a),a.children&&e(a.children,t)})}(a,a=>{a.children=e.filter(e=>e.parentId===a.id)}),a}const Zf=new Set([tf.Text]),eg=new Set([tf.Text,tf.Numeric,tf.RiskMatrix,tf.Burndown,tf.PerformanceColumns]),ag=new Set([tf.Text,tf.RiskMatrix,tf.Burndown,tf.PerformanceColumns]);function tg({config:r,viewOnly:n=!1,complement:l,complementPosition:c="before-options",queryUrlBuilder:d,onRefresh:u,onExport:m,onToggleOnlyMine:h,className:p}){const[f,g]=i(r.onlyMine??!1),v=Zf.has(r.typeId),x=!eg.has(r.typeId),b=!ag.has(r.typeId),y=s(()=>{if(!r.jsonRules||r.typeId===tf.PerformanceColumns)return!1;try{const e=JSON.parse(r.jsonRules);return e?.rules?.rules?.length>0}catch{return!1}},[r.jsonRules,r.typeId]),N=s(()=>d?.(r)??"#",[d,r]),w=o(()=>{const e=!f;g(e),h?.(e)},[f,h]),C=[];return f&&C.push("Somente meus"),r.onlyLate&&C.push("Somente atrasados"),y&&C.push("Filtro avançado"),a("div",{className:Ki("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",p),children:[a("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===c&&l,a("div",{className:"flex min-w-0 flex-col",children:[a(So,{children:[e(Ao,{asChild:!0,children:e("span",{className:"block truncate",children:r.title})}),e(Do,{children:r.title})]}),C.length>0&&e("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:C.join(" | ")})]}),"after-title"===c&&l]}),!n&&a("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===c&&l,a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e(Ea,{className:"h-3.5 w-3.5"})})}),a(xo,{align:"end",className:"w-48",children:[r.canUpdate&&a(bo,{onClick:()=>r.onEdit?.(r.id),children:[e(W,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!v&&a(bo,{onClick:u,children:[e(Je,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&a(bo,{disabled:r.noData,onClick:m,children:[e(Ce,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!v&&a(bo,{disabled:!r.openQueryEnabled,onClick:()=>window.open(N,"_blank"),children:[e(Ze,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),b&&a(t,{children:[e(Co,{}),a(bo,{onClick:w,children:[f&&e(P,{className:"mr-2 h-3.5 w-3.5"}),!f&&e("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),r.canUpdate&&a(t,{children:[e(Co,{}),a(bo,{onClick:()=>r.onDuplicate?.(r.id),children:[e(ye,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),a(bo,{className:"text-destructive",onClick:()=>r.onRemove?.(r.id),children:[e(q,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===c&&l]})]})}function rg({config:t,queryUrl:r,className:n}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[e(Xe,{className:"h-12 w-12 text-muted-foreground/50"}),e("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),e("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),a("p",{className:"mt-2 text-xs",children:[r&&e("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),r&&t.canUpdate&&e("span",{className:"text-muted-foreground",children:" ou "}),t.canUpdate&&e("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>t.onEdit?.(t.id),children:"revisar o painel"})]})]})}function ng({panelType:t,className:r}){const n=t===tf.Burndown;return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[e(so,{className:"h-10 w-10 text-muted-foreground/40"}),n&&e("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function ig({hasRemovedColumn:t=!1,className:r}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[e("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:"Não há dados para exibir"}),e("p",{className:"text-sm text-muted-foreground lg:text-xs",children:t?"A coluna utilizada neste painel foi removida da consulta.":"A consulta não retornou itens para o seu perfil."})]})}function sg({onRemove:t,className:r}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[e(Xe,{className:"h-12 w-12 text-muted-foreground/50"}),e("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),e("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),t&&e("p",{className:"mt-2 text-xs",children:e("button",{type:"button",className:"underline hover:text-foreground",onClick:t,children:"Remover painel"})})]})}const og={[jp.Count]:"Contagem",[jp.Sum]:"Soma",[jp.Average]:"Média",[jp.DistinctCount]:"Contagem distinta",[jp.Max]:"Valor máximo",[jp.Min]:"Valor mínimo"};function lg({config:t,state:r,value:n,label:i,viewOnly:s=!1,onClick:o,onRefresh:l,queryUrl:c,queryUrlBuilder:d,className:u}){const m=i??og[t.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=jf.includes(a.field),r=a.aggregationType===jp.Count||a.aggregationType===jp.DistinctCount;return t&&!r?Xf.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?r?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(n,t);return a("div",{className:Ki("flex h-full flex-col",u),children:[e(tg,{config:t,viewOnly:s,onRefresh:l,queryUrlBuilder:d}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&a("div",{className:Ki("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,children:[e("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:h}),m&&e("span",{className:"text-xs text-muted-foreground mt-1",children:m})]}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:c}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function cg({config:t,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:s,queryUrl:o,queryUrlBuilder:l,className:c}){const d=n??t.textTypeString??"";return a("div",{className:Ki("flex h-full flex-col",c),children:[e(tg,{config:t,viewOnly:i,onRefresh:s,queryUrlBuilder:l}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:d}}),r===Nf.Error&&e(rg,{config:t,queryUrl:o})]})}function dg({config:t,state:r,data:n=[],columns:i=[],viewOnly:l=!1,onRowClick:c,onRefresh:d,onExport:u,queryUrl:m,queryUrlBuilder:h,enableRowLinks:p=!0,className:f}){const g=s(()=>i.filter(e=>!1!==e.visible),[i]),v=o(e=>{if(c)c(e);else if(p){const a=Wf(e);a&&window.open(qf(a),"_blank")}},[c,p]);return a("div",{className:Ki("flex h-full flex-col",f),children:[e(tg,{config:t,viewOnly:l,onRefresh:d,onExport:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 overflow-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:e("tr",{children:g.map(a=>e("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:a.header||a.columnLabel||a.columnName},a.columnName))})}),e("tbody",{children:n.map((a,t)=>{const r=p&&!!Wf(a);return e("tr",{className:Ki("border-b border-border/50 transition-colors hover:bg-muted/30",(r||c)&&"cursor-pointer"),onClick:()=>v(a),children:g.map(t=>e("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:t.render?t.render(a[t.columnName],a):ug(a[t.columnName],t)},t.columnName))},t)})})]})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function ug(e,a){return null==e?"":e instanceof Date?"datetime"===a.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const mg=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function hg({config:t,variant:r,state:n,data:i=[],series:o,colors:l,categoryKey:c="key",yAxisFormat:d,viewOnly:u=!1,onPointClick:m,onRefresh:h,onExport:p,queryUrl:f,queryUrlBuilder:g,className:v}){const x=l?.length?l:t.hexColors?.length?t.hexColors:mg,b=s(()=>o?.length?o:[{dataKey:"value",name:t.title}],[o,t.title]),y="bar"===r,N="stacked-column"===r,w=s(()=>{if(d)return e=>d.replace("{value}",e.toLocaleString("pt-BR"))},[d]);return a("div",{className:Ki("flex h-full flex-col",v),children:[e(tg,{config:t,viewOnly:u,onRefresh:h,onExport:p,queryUrlBuilder:g}),n===Nf.Loading&&e(ng,{}),n===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:pg({variant:r,data:i,series:b,colors:x,categoryKey:c,isHorizontalBar:y,isStacked:N,yAxisTickFormatter:w,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:m})})}),n===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),n===Nf.Error&&e(rg,{config:t,queryUrl:f}),n===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function pg({variant:t,data:r,series:n,colors:i,categoryKey:s,isHorizontalBar:o,isStacked:l,yAxisTickFormatter:c,tooltipFormatter:d,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},h=e(Ut,{dataKey:o?void 0:s,type:o?"number":"category",...m,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?c:void 0}),p=e(jt,{dataKey:o?s:void 0,type:o?"category":"number",...m,width:o?100:60,tickFormatter:o?void 0:c}),f=e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=e(Bt,{formatter:d,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?e($t,{wrapperStyle:{fontSize:"11px"}}):null,x=u?(e,a)=>u(r[a],a):void 0;return"bar"===t||"column"===t||"stacked-column"===t?a(Vt,{data:r,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>e(qt,{dataKey:a.dataKey,name:a.name||a.dataKey,fill:a.color||i[t%i.length],stackId:l?a.stackId||"stack":void 0,radius:l?void 0:[2,2,0,0],onClick:x,cursor:u?"pointer":void 0},a.dataKey))]}):"area"===t?a(Wt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>{const r=a.color||i[t%i.length];return e(Ht,{type:"monotone",dataKey:a.dataKey,name:a.name||a.dataKey,stroke:r,fill:r,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:u?"pointer":void 0}},a.dataKey)})]}):a(Gt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>e(Yt,{type:"monotone",dataKey:a.dataKey,name:a.name||a.dataKey,stroke:a.color||i[t%i.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:u?"pointer":void 0}},a.dataKey))]})}const fg=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function gg({config:t,state:r,data:n=[],colors:i,viewOnly:o=!1,onSliceClick:l,onRefresh:c,onExport:d,queryUrl:u,queryUrlBuilder:m,className:h}){const p=i?.length?i:t.hexColors?.length?t.hexColors:fg,f=s(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=s(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return a("div",{className:Ki("flex h-full flex-col",h),children:[e(tg,{config:t,viewOnly:o,onRefresh:c,onExport:d,queryUrlBuilder:m}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Kt,{children:[e(Qt,{data:f,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:a})=>`${e??""}: ${(100*(a??0)).toFixed(0)}%`,labelLine:!0,onClick:l?(e,a)=>l(n[a],a):void 0,cursor:l?"pointer":void 0,children:f.map((a,t)=>e(Xt,{fill:p[t%p.length]},t))}),e(Bt,{formatter:e=>{const a="number"==typeof e?e:0,t=g>0?(a/g*100).toFixed(1):"0";return`${a.toLocaleString("pt-BR")} (${t}%)`}}),e($t,{wrapperStyle:{fontSize:"11px"}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:u}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function vg({config:t,state:r,data:n=[],barColor:i,lineColor:o="#e31a1c",viewOnly:l=!1,onPointClick:c,onRefresh:d,onExport:u,queryUrl:m,queryUrlBuilder:h,className:p}){const f=t.hexColors?.length?t.hexColors:["#1f78b4"],g=i??f[0],v=s(()=>{const e=[...n].sort((e,a)=>(a.value??0)-(e.value??0)),a=e.reduce((e,a)=>e+(a.value??0),0);let t=0;return e.map(e=>(t+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:a>0?Math.round(t/a*100):0}))},[n]);return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:l,onRefresh:d,onExport:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Jt,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),e(jt,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),e(jt,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),e(Bt,{formatter:(e,a)=>"% Acumulado"===a?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(qt,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:g,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),e(Yt,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function xg({config:t,state:r,data:n=[],executedLabel:i="Trabalho executado",plannedLabel:s="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:c=!1,onRefresh:d,queryUrl:u,queryUrlBuilder:m,className:h}){return a("div",{className:Ki("flex h-full flex-col",h),children:[e(tg,{config:t,viewOnly:c,onRefresh:d,queryUrlBuilder:m}),r===Nf.Loading&&e(ng,{panelType:tf.Burndown}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Wt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),e(jt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),e(Bt,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(Ht,{type:"monotone",dataKey:"executedPercentage",name:i,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),e(Ht,{type:"monotone",dataKey:"plannedPercentage",name:s,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:u}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function bg({config:t,state:r,data:n=[],executedLabel:i="Trabalho executado",plannedLabel:s="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:c=!1,onPointClick:d,onRefresh:u,queryUrl:m,queryUrlBuilder:h,className:p}){return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:c,onRefresh:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Vt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),e(jt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),e(Bt,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(qt,{dataKey:"executedWork",name:i,fill:o,radius:[2,2,0,0],onClick:d?(e,a)=>d(n[a],a):void 0,cursor:d?"pointer":void 0}),e(qt,{dataKey:"plannedWork",name:s,fill:l,radius:[2,2,0,0]})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function yg({config:t,state:r,rule:n,risks:i=[],matrixViewType:o=ff.Quantity,viewOnly:l=!1,onCellClick:c,onRiskClick:d,onRefresh:u,queryUrl:m,queryUrlBuilder:h,className:p}){const f=s(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=s(()=>{const e={};return i.forEach(a=>{const t=`${a.parameterYPosition}-${a.parameterXPosition}`;e[t]||(e[t]=[]),e[t].push(a)}),e},[i]);return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:l,onRefresh:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&n&&e("div",{className:"flex-1 overflow-auto p-4",children:a("div",{className:"flex gap-4 items-stretch min-w-fit",children:[e("div",{className:"flex items-center justify-center",children:e("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:n.name_y})}),a("div",{className:"flex-1",children:[a("div",{className:"flex mb-1",children:[e("div",{className:"w-16 shrink-0"}),e("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.threat_strategy_type_name}),!n.disable_opportunities&&e("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.opportunity_strategy_type_name})]}),f.map((t,r)=>a("div",{className:"flex",children:[e("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:t.name}),g.map((i,s)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,t),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(s,r);return a("div",{className:Ki("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(c||d)&&l.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:u},onClick:()=>l.length>0&&c?.(i,t,l),children:[o===ff.Quantity&&l.length>0&&a("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),o===ff.AllRisksList&&l.map(t=>a(So,{children:[e(Ao,{asChild:!0,children:e("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:e=>{e.stopPropagation(),d?.(t)},children:t.code})}),a(Do,{className:"max-w-[250px]",children:[a("p",{className:"font-medium",children:[t.code," - ",t.name]}),t.analysisDate&&a("p",{className:"text-xs mt-1",children:["Última análise: ",e("strong",{children:t.analysisDate})]}),t.strategy&&a("p",{className:"text-xs",children:["Estratégia: ",e("strong",{children:t.strategy})]}),t.resultName&&a("p",{className:"text-xs",children:["Criticidade: ",e("strong",{style:{backgroundColor:u},className:"px-1 rounded",children:t.resultName})]})]})]},t.code))]},i.position)})]},t.position)),a("div",{className:"flex",children:[e("div",{className:"w-16 shrink-0"}),g.map(a=>e("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:a.name},a.position))]}),e("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:n.name_x})]})]})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}const Ng=Object.freeze({Translate:{toString(e){if(!e)return;const{x:a,y:t}=e;return"translate3d("+(a?Math.round(a):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:a,scaleY:t}=e;return"scaleX("+a+") scaleY("+t+")"}},Transform:{toString(e){if(e)return[Ng.Translate.toString(e),Ng.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function wg(e){switch(e){case tf.Bar:case tf.Column:case tf.Pie:case tf.List:case tf.Line:case tf.Area:case tf.Text:case tf.StackedColumn:return{x:4,y:2};case tf.Pareto:case tf.RiskMatrix:case tf.Burndown:case tf.PerformanceColumns:return{x:8,y:2};case tf.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function Cg(e){switch(Number(e)){case tf.Area:case tf.Bar:case tf.Column:case tf.Line:case tf.Numeric:case tf.Pie:case tf.Text:return{x:1,y:1};default:return{x:2,y:2}}}function kg({panel:t,columns:r,cellHeight:n,cellGap:i,allowDragging:o,children:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=pr({id:t.id,disabled:!o}),f=s(()=>({gridColumn:`${t.col+1} / span ${t.sizeX}`,gridRow:`${t.row+1} / span ${t.sizeY}`,minHeight:t.sizeY*n+(t.sizeY-1)*i+"px",transform:Ng.Transform.toString(m),transition:h,zIndex:p?50:void 0,opacity:p?.85:1}),[t,r,n,i,m,h,p]);return a("div",{ref:u,style:f,className:Ki("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",p&&"shadow-lg ring-2 ring-primary/20"),...c,children:[e("div",{className:Ki("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?d:{}}),e("div",{className:"h-full",children:l})]})}function _g({panels:t,columns:r=8,cellHeight:n=160,cellGap:l=10,allowDragging:c=!1,showGridLines:d=!1,renderPanel:u,onLayoutChange:m,className:h}){const[p,f]=i(t);s(()=>{f(t)},[t]);const g=or(lr(cr,{activationConstraint:{distance:8}})),v=s(()=>0===p.length?1:Math.max(...p.map(e=>e.row+e.sizeY)),[p]),x=s(()=>p.map(e=>e.id),[p]),b=o(e=>{const{active:a,over:t}=e;if(!t||a.id===t.id)return;const r=p.findIndex(e=>e.id===a.id),n=p.findIndex(e=>e.id===t.id);if(-1===r||-1===n)return;const i=[...p],s={...i[r]},o={...i[n]},l=s.col,c=s.row;s.col=o.col,s.row=o.row,o.col=l,o.row=c,i[r]=s,i[n]=o,f(i),m?.(i)},[p,m]),y=s(()=>({display:"grid",gridTemplateColumns:`repeat(${r}, 1fr)`,gridTemplateRows:`repeat(${v}, ${n}px)`,gap:`${l}px`}),[r,v,n,l]);return 0===p.length?a("div",{className:Ki("flex flex-col items-center justify-center py-16 text-center",h),children:[e("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),e("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):e(dr,{sensors:g,collisionDetection:ur,onDragEnd:b,children:e(mr,{items:x,strategy:hr,children:e("div",{style:y,className:Ki("relative w-full",d&&"bg-muted/30",h),children:p.map(a=>e(kg,{panel:a,columns:r,cellHeight:n,cellGap:l,allowDragging:c,children:u(a.id)},a.id))})})})}const Sg={[tf.Bar]:"bar",[tf.Column]:"column",[tf.StackedColumn]:"stacked-column",[tf.Area]:"area",[tf.Line]:"line",[tf.EvolutionLine]:"evolution-line"};function Ag({config:t,state:r,data:n,numericValue:i,listColumns:s,cartesianData:o,cartesianSeries:l,burndownData:c,performanceData:d,matrixRule:u,matrixRisks:m,onPanelClick:h}){const p=Sg[t.typeId];if(p)return e(hg,{config:t,variant:p,state:r,data:o,series:l});switch(t.typeId){case tf.Numeric:return e(lg,{config:t,state:r,value:i});case tf.Text:return e(cg,{config:t,state:r});case tf.List:return e(dg,{config:t,state:r,data:n,columns:s??[]});case tf.Pie:return e(gg,{config:t,state:r,data:n});case tf.Pareto:return e(vg,{config:t,state:r,data:n});case tf.Burndown:return e(xg,{config:t,state:r,data:c});case tf.PerformanceColumns:return e(bg,{config:t,state:r,data:d});case tf.RiskMatrix:return e(yg,{config:t,state:r,rule:u,risks:m??[]});default:return a("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",t.typeId,")"]})}}function Dg({dashboard:t,panels:r,pages:n,activePageId:l,canEdit:c=!1,isFullscreen:d=!1,isLoading:u=!1,getPanelData:m,onRefresh:h,onToggleFullscreen:p,onToggleFavorite:f,onEdit:g,onShare:v,onAddPanel:x,onEditPanel:b,onRemovePanel:y,onDuplicatePanel:N,onLayoutChange:w,onPageChange:C,toolbarActions:k,className:_}){const[S,A]=i(!1),D=t.idViewType===of.Carousel,P=s(()=>r,[r,D,l]),E=s(()=>P.map(e=>{const a=Cg(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:a.x,minSizeY:a.y}}),[P]),T=o(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:c,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:b,onRemove:y,onDuplicate:N}),[c,b,y,N]),I=o(()=>{S||u||(A(!0),h?.(),setTimeout(()=>A(!1),3e4))},[S,u,h]),M=o(t=>{const r=P.find(e=>e.id===t);if(!r)return null;const n=T(r),i=m?.(t)??{state:Nf.Loaded};return a("div",{className:"flex flex-col h-full",children:[e(tg,{config:n,onRefresh:()=>{}}),e("div",{className:"flex-1 min-h-0 p-2",children:e(Ag,{config:n,...i})})]})},[P,T,m,c,b,y,N]);return a("div",{className:Ki("flex flex-col h-full",d&&"fixed inset-0 z-50 bg-background",_),children:[a("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3 min-w-0",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:t.title}),t.responsibleName&&!d&&e("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:t.responsibleName})]}),a("div",{className:"flex items-center gap-1",children:[k,h&&e("button",{onClick:I,disabled:S||u,className:Ki("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:S?"Aguarde para atualizar novamente":"Atualizar",children:e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),p&&e("button",{onClick:p,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:d?"Sair do fullscreen":"Fullscreen",children:e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",d?{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),c&&!d&&v&&e("button",{onClick:v,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),f&&!d&&e("button",{onClick:f,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:t.isFavorite?"Remover favorito":"Favoritar",children:e("svg",{className:Ki("h-4 w-4",t.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),D&&n&&n.length>1&&e("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:n.map(a=>e("button",{onClick:()=>C?.(a.id),className:Ki("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",l===a.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:a.name||`Dashboard ${a.position}`},a.id))}),c&&!d&&x&&e("div",{className:"flex justify-center py-3",children:a("button",{onClick:x,className:Ki("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),u&&e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!u&&e("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:e(_g,{panels:E,allowDragging:c,showGridLines:c,renderPanel:M,onLayoutChange:w})})]})}function Pg(e,a=hf.PtBr){switch(a){case hf.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case hf.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function Eg(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const Tg=[{value:Tf.All,label:"Todos"},{value:Tf.OnlyMine,label:"Meus dashboards"},{value:Tf.Favorites,label:"Favoritos"}];function Ig({dashboards:r,limit:n,isLoading:l=!1,language:c=hf.PtBr,canAdd:d=!1,canEdit:u=!1,canRemove:m=!1,onOpen:h,onEdit:p,onShare:f,onDuplicate:g,onRemove:v,onAdd:x,onToggleFavorite:b,onRefresh:y,onSearch:N,onQuickFilterChange:w,toolbarExtra:C,className:k}){const[_,S]=i(""),[A,D]=i(Tf.All),[P,E]=i(null),T=o(e=>{S(e),N?.(e)},[N]),I=o(e=>{D(e),w?.(e)},[w]),M=s(()=>{let e=r;if(_){const a=_.toLowerCase();e=e.filter(e=>e.code?.toLowerCase().includes(a)||Pg(e,c).toLowerCase().includes(a)||e.responsibleName?.toLowerCase().includes(a))}switch(A){case Tf.OnlyMine:break;case Tf.Favorites:e=e.filter(e=>e.isFavorite)}return e},[r,_,A,c]);return a("div",{className:Ki("flex flex-col h-full",k),children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3",children:[e("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),n&&a("span",{className:"text-xs text-muted-foreground",children:["(",n.countDashboards,"/",n.maxDashboards,")"]})]}),a("div",{className:"flex items-center gap-2",children:[a("div",{className:"relative",children:[a("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"11",cy:"11",r:"8"}),e("path",{d:"m21 21-4.3-4.3"})]}),e("input",{type:"text",placeholder:"Buscar...",value:_,onChange:e=>T(e.target.value),className:Ki("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),C,d&&x&&a("button",{onClick:x,className:Ki("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),e("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:Tg.map(a=>e("button",{onClick:()=>I(a.value),disabled:l,className:Ki("px-3 py-1.5 text-sm rounded-md transition-colors",A===a.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:a.label},a.value))}),l&&e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!l&&e("div",{className:"flex-1 overflow-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:a("tr",{children:[e("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:e("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),e("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:a("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),e("th",{className:"w-12 px-3 py-2"})]})}),a("tbody",{children:[0===M.length&&e("tr",{children:e("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),M.map(r=>a("tr",{onClick:()=>h?.(r),className:Ki("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[e("td",{className:"px-3 py-2",children:e("button",{onClick:e=>{e.stopPropagation(),b?.(r)},className:"p-1 hover:bg-accent rounded transition-colors",children:e("svg",{className:Ki("h-4 w-4",r.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),e("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:r.code}),e("td",{className:"px-3 py-2 text-foreground font-medium",children:Pg(r,c)}),e("td",{className:"px-3 py-2 text-muted-foreground",children:r.responsibleName}),e("td",{className:"px-3 py-2 text-center",children:r.hasSharedIcon&&a("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:Eg(r.lastModified)}),e("td",{className:"px-3 py-2",children:e("span",{className:Ki("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",r.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:r.isActive?"Ativo":"Inativo"})}),e("td",{className:"px-3 py-2",children:a("div",{className:"relative",children:[e("button",{onClick:e=>{e.stopPropagation(),E(P===r.id?null:r.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:a("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"12",cy:"5",r:"1"}),e("circle",{cx:"12",cy:"12",r:"1"}),e("circle",{cx:"12",cy:"19",r:"1"})]})}),P===r.id&&a(t,{children:[e("div",{className:"fixed inset-0 z-40",onClick:()=>E(null)}),a("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[e("button",{onClick:e=>{e.stopPropagation(),E(null),h?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),u&&e("button",{onClick:e=>{e.stopPropagation(),E(null),p?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),u&&e("button",{onClick:e=>{e.stopPropagation(),E(null),f?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),e("button",{onClick:e=>{e.stopPropagation(),E(null),g?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),m&&a(t,{children:[e("div",{className:"my-1 border-t border-border"}),e("button",{onClick:e=>{e.stopPropagation(),E(null),v?.(r)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},r.id))]})]})})]})}const Mg=[{value:nf.NotUpdate,label:"Não atualizar"},{value:nf.FiveMinutes,label:"5 minutos"},{value:nf.TenMinutes,label:"10 minutos"},{value:nf.FifteenMinutes,label:"15 minutos"},{value:nf.ThirtyMinutes,label:"30 minutos"},{value:nf.OneHour,label:"1 hora"}],Rg=[{value:of.NormalPage,label:"Página normal"},{value:of.Carousel,label:"Carrossel"}],Lg=[{value:Hp.FiveSeconds,label:"5 segundos"},{value:Hp.TenSeconds,label:"10 segundos"},{value:Hp.FifteenSeconds,label:"15 segundos"},{value:Hp.ThirtySeconds,label:"30 segundos"},{value:Hp.OneMinute,label:"1 minuto"},{value:Hp.ThreeMinutes,label:"3 minutos"},{value:Hp.FiveMinutes,label:"5 minutos"},{value:Hp.TenMinutes,label:"10 minutos"}],zg=[{value:uf.NotShared,label:"Não compartilhado",description:"Somente o responsável terá acesso"},{value:uf.SharedWithAllCollaborators,label:"Compartilhado com todos os colaboradores da unidade",description:"Todos os colaboradores terão acesso"},{value:uf.SharedWithUsersGroupsPlacesCollaborators,label:"Compartilhado com grupos, locais e colaboradores",description:"Selecione grupos, locais e colaboradores específicos"}],Fg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function Ug({dashboard:t,initialTab:r=cf.General,isSaving:n=!1,isQualitfy:l=!1,users:c=[],groups:d=[],places:u=[],collaborators:m=[],onSave:h,onCancel:p,className:f}){const g=!!t,[v,x]=i(r),[b,y]=i({"pt-br":!!t?.titlePtBr||!g,en:!!t?.titleEnUs,es:!!t?.titleEsEs}),[N,w]=i(t?.titlePtBr??""),[C,k]=i(t?.titleEnUs??""),[_,S]=i(t?.titleEsEs??""),[A,D]=i(t?.responsibleId??""),[P,E]=i(t?.isActive??!0),[T,I]=i(t?.idUpdateTime??nf.NotUpdate),[M,R]=i(t?.idViewType??of.NormalPage),[L,z]=i(t?.idPageTime??Hp.FifteenSeconds),[F,U]=i(t?.idShare??uf.NotShared),[j,O]=i(t?.groups??[]),[B,$]=i(t?.places??[]),[V,q]=i(t?.collaborators??[]),W=M===of.Carousel,H=b["pt-br"]||b.en||b.es,G=s(()=>!!H&&(!(b["pt-br"]&&!N.trim())&&(!(b.en&&!C.trim())&&!(b.es&&!_.trim()))),[H,b,N,C,_]),Y=o(e=>{y(a=>({...a,[e]:!a[e]}))},[]),K=o(()=>{G&&!n&&h?.({titlePtBr:b["pt-br"]?N:"",titleEnUs:b.en?C:"",titleEsEs:b.es?_:"",responsibleId:A||void 0,isActive:P,idUpdateTime:T,idViewType:M,idPageTime:W?L:null,idShare:F,groups:F===uf.SharedWithUsersGroupsPlacesCollaborators?j:[],places:F===uf.SharedWithUsersGroupsPlacesCollaborators?B:[],collaborators:F===uf.SharedWithUsersGroupsPlacesCollaborators?V:[]})},[G,n,h,b,N,C,_,A,P,T,M,L,W,F,j,B,V]);return a("div",{className:Ki("flex flex-col h-full bg-background",f),children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3",children:[e("h2",{className:"text-lg font-semibold text-foreground",children:g?"Editar Dashboard":"Novo Dashboard"}),g&&t&&e("span",{className:"text-sm text-muted-foreground",children:t.code})]}),a("div",{className:"flex items-center gap-2",children:[e("button",{onClick:p,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),a("button",{onClick:K,disabled:!G||n,className:Ki("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[n?e("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),a("div",{className:"flex border-b border-border bg-card",children:[e("button",{onClick:()=>x(cf.General),className:Ki("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",v===cf.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),e("button",{onClick:()=>x(cf.Share),className:Ki("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",v===cf.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),a("div",{className:"flex-1 overflow-auto p-6",children:[v===cf.General&&a("div",{className:"max-w-2xl space-y-6",children:[a("div",{className:"space-y-2",children:[e("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),e("div",{className:"flex gap-2",children:Fg.map(a=>e("button",{onClick:()=>Y(a.key),className:Ki("px-3 py-1 text-xs rounded-md border transition-colors",b[a.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:a.label},a.key))}),!H&&e("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),b["pt-br"]&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),e("input",{value:N,onChange:e=>w(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[N.length,"/200"]})]}),b.en&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),e("input",{value:C,onChange:e=>k(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[C.length,"/200"]})]}),b.es&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),e("input",{value:_,onChange:e=>S(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[_.length,"/200"]})]}),!t?.isStandard&&c.length>0&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),a("select",{value:A,onChange:e=>D(e.target.value),disabled:!g,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[e("option",{value:"",children:"Selecione..."}),c.map(a=>e("option",{value:a.id,children:a.name},a.id))]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),e("select",{value:T,onChange:e=>I(Number(e.target.value)),disabled:l,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Mg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]}),a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Situação"}),a("div",{className:"flex items-center gap-3 h-10",children:[e("button",{onClick:()=>E(!P),disabled:t?.isGeneralViewUse,className:Ki("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",P?"bg-primary":"bg-muted","disabled:opacity-50"),children:e("span",{className:Ki("inline-block h-4 w-4 rounded-full bg-white transition-transform",P?"translate-x-6":"translate-x-1")})}),e("span",{className:"text-sm text-foreground",children:P?"Ativo":"Inativo"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),e("select",{value:M,onChange:e=>R(Number(e.target.value)),disabled:l||W,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Rg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]}),W&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),e("select",{value:L??"",onChange:e=>z(Number(e.target.value)),className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:Lg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]})]})]}),v===cf.Share&&a("div",{className:"max-w-2xl space-y-6",children:[a("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[a("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("path",{d:"M12 16v-4"}),e("path",{d:"M12 8h.01"})]}),e("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),e("div",{className:"space-y-3",children:zg.map(r=>a("label",{className:Ki("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",F===r.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",t?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[e("input",{type:"radio",name:"shareType",value:r.value,checked:F===r.value,onChange:()=>U(r.value),disabled:t?.isGeneralViewUse,className:"mt-1 accent-primary"}),a("div",{children:[e("p",{className:"text-sm font-medium text-foreground",children:r.label}),e("p",{className:"text-xs text-muted-foreground",children:r.description})]})]},r.value))}),F===uf.SharedWithUsersGroupsPlacesCollaborators&&a("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",j.length,")"]}),e("select",{multiple:!0,value:j,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);O(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:d.map(a=>e("option",{value:a.id,children:a.name},a.id))})]}),a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Locais (",B.length,")"]}),e("select",{multiple:!0,value:B,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);$(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:u.map(a=>e("option",{value:a.id,children:a.name},a.id))})]}),a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",V.length,")"]}),e("select",{multiple:!0,value:V,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);q(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:m.map(a=>e("option",{value:a.id,children:a.name},a.id))})]})]})]})]})]})}function jg({dashboards:t,limit:r,generalView:n,language:l=hf.PtBr,isLoading:c=!1,canAdd:d=!1,canEdit:m=!1,canRemove:h=!1,canEditStandard:p=!1,activePanels:f=[],activePages:g=[],getPanelData:v,users:x=[],groups:b=[],places:y=[],collaborators:N=[],isSaving:w=!1,onOpen:C,onBackToList:k,onRefresh:_,onRefreshList:S,onToggleFavorite:A,onSave:D,onUpdate:P,onRemove:E,onDuplicate:T,onShare:I,onAddPanel:M,onEditPanel:R,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onSearch:U,onQuickFilterChange:j,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:V,viewToolbarActions:q,className:W}){const[H,G]=i({mode:"list"}),Y=B??H,K=o(e=>{$?$(e):G(e)},[$]),Q=s(()=>"view"===Y.mode||"edit"===Y.mode||"share"===Y.mode?t.find(e=>e.id===Y.dashboardId)??null:null,[t,Y]),[X,J]=i(!1),[Z,ee]=i(g[0]?.id);u(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),u(()=>{if("view"!==Y.mode||!Q||Q.idViewType!==of.Carousel||g.length<=1)return;const e=function(e){switch(e){case Hp.FiveSeconds:return 5e3;case Hp.TenSeconds:return 1e4;case Hp.FifteenSeconds:return 15e3;case Hp.ThirtySeconds:return 3e4;case Hp.OneMinute:return 6e4;case Hp.ThreeMinutes:return 18e4;case Hp.FiveMinutes:return 3e5;case Hp.TenMinutes:return 6e5;default:return 15e3}}(Q.idPageTime),a=setInterval(()=>{ee(e=>{const a=(g.findIndex(a=>a.id===e)+1)%g.length;return g[a]?.id})},e);return()=>clearInterval(a)},[Y,Q,g]);const ae=o(e=>{K({mode:"view",dashboardId:e.id}),ee(void 0),C?.(e)},[K,C]),te=o(()=>{K({mode:"list"}),J(!1),k?.()},[K,k]),re=o(()=>{K({mode:"create"})},[K]),ne=o(e=>{K({mode:"edit",dashboardId:e.id})},[K]),ie=o(e=>{K({mode:"share",dashboardId:e.id})},[K]),se=o(e=>{"edit"===Y.mode||"share"===Y.mode?P?.(Y.dashboardId,e):D?.(e)},[Y,D,P]),oe=o(()=>{"edit"===Y.mode||"share"===Y.mode?K({mode:"view",dashboardId:Y.dashboardId}):K({mode:"list"})},[Y,K]),le=o(()=>{Q&&A?.(Q)},[Q,A]),ce=o(()=>{Q&&ne(Q)},[Q,ne]),de=o(()=>{Q&&ie(Q)},[Q,ie]);return a("div",{className:Ki("flex flex-col h-full",W),children:["list"===Y.mode&&e(Ig,{dashboards:t,limit:r,isLoading:c,language:l,canAdd:d,canEdit:m,canRemove:h,onOpen:ae,onEdit:ne,onShare:ie,onDuplicate:T,onRemove:E,onAdd:re,onToggleFavorite:A,onRefresh:S,onSearch:U,onQuickFilterChange:j,toolbarExtra:V,className:"flex-1"}),"view"===Y.mode&&Q&&a("div",{className:"flex flex-col h-full",children:[!X&&a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[a("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),n?.dashboardId===Q.id&&a("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[a("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),e("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),m&&O&&n?.dashboardId!==Q.id&&e("button",{onClick:()=>O(Q.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),e(Dg,{dashboard:Q,panels:f,pages:g,activePageId:Z,canEdit:m||p&&!!Q.isStandard,isFullscreen:X,isLoading:c,getPanelData:v,onRefresh:_,onToggleFullscreen:()=>J(e=>!e),onToggleFavorite:le,onEdit:ce,onShare:de,onAddPanel:M,onEditPanel:R,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onPageChange:ee,toolbarActions:q,className:"flex-1"})]}),"create"===Y.mode&&a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:a("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),e(Ug,{users:x,groups:b,places:y,collaborators:N,isSaving:w,onSave:se,onCancel:oe,className:"flex-1"})]}),("edit"===Y.mode||"share"===Y.mode)&&Q&&a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:a("button",{onClick:oe,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),e(Ug,{dashboard:Q,initialTab:"share"===Y.mode?cf.Share:cf.General,users:x,groups:b,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!p,onSave:se,onCancel:oe,className:"flex-1"})]})]})}const Og=({manager:r,columns:n,onEdit:i,onView:s,onToggleStatus:o,onDelete:l,renderActions:c,customRowActions:d,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:x=!0,showSearch:b=!1,searchValue:y,onSearchChange:N,searchPlaceholder:w,bulkActions:C=[],onBulkDelete:k,filters:_,gridColumns:S=3,renderCard:A,viewMode:D,onViewModeChange:P,listCardRenderer:E,gridCardRenderer:T,showViewToggle:I=!1})=>{const{setSearchVisible:M}=zl(),R=void 0!==v?!v:x;u(()=>{if(!b)return M(!0),()=>M(!1)},[M,b]);const L=h||g.length>0||b||m||_||I,z=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=D||"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=R&&L?e(Pc,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:b,searchValue:y,onSearchChange:N,searchPlaceholder:w,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:z,onClearSelection:r.clearSelection,customActions:g,filters:_,viewMode:F,onViewModeChange:P,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(Ql,{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(ac,{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:Ki("grid gap-4",j),children:r.entities.map(u=>{const h=(e=>U&&E?E(e):!U&&T?T(e):A?A(e):null)(u);return a(nc,{children:[e(ic,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(u.id):i?.(u)},children:h}):e(is,{className:Ki("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(cs,{className:Ki("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:Ki(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Ec,{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||s||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(u):e(yc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(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(Ec,{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:Ki("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||s||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(u):e(yc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(u):void 0,isActive:u.is_actived,customActions:d?d(u):[]})})]})]})]})})}),e(mc,{className:"w-[160px]",children:e(bc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(u):void 0,isActive:u.is_actived,canDelete:!!l,customActions:d?d(u):[],renderAs:"context"})})]},u.id)})})})]})};function Bg({data:t,columns:r,sortField:n,sortDirection:i,onSort:o,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:x=!0,onColumnResize:b,enableColumnReorder:y=!1,onReorderColumns:N,storageKey:w}){const{t:C}=tt(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:_,isDragging:S,activeColumn:A,handleMouseDown:D}=Cc({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:w?`${w}-columns`:void 0,onResize:b,enabled:x}),P=Mc({enabled:y&&!!N,onReorder:N??(()=>{})}),E=s(()=>{if(x)return r.map(e=>`${_[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,x,_]);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($o,{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:k})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(Bl,{className:m,children:[e($l,{className:"sticky top-0 bg-background z-10",children:a(Wl,{children:[h&&e(Hl,{className:"w-[40px]",children:e(ao,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const s=x&&!1!==t.resizable,l=A===String(t.key),c=y&&!!N,d=c?P.getDragProps(r):{},u=P.dragFromIndex===r,m=P.dragOverIndex===r&&P.dragFromIndex!==r;return a(Hl,{className:Ki(t.className,"relative transition-opacity",t.sortable&&"cursor-pointer",c&&P.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[r]},...d,children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?null:e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),s&&e(rc,{direction:"horizontal",onMouseDown:e=>D(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(Hl,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(Vl,{children:t.map(t=>a(Wl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(Gl,{children:e(ao,{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(Gl,{className:a.className,children:e(tc,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(Gl,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function $g({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:o=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=tt(),h=s(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:B,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?$:V,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,o,l,c,m]);return 0===h.length?null:"dropdown"===d?e(_o,{delayDuration:200,children:a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(xo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(Po,{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(bo,{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(es,{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 Vg({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:s=!0,layout:o="horizontal"}){const{t:l}=tt(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),s&&c&&i&&a(es,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function qg(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 Wg({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:s,onDropCell:o,className:l}){return e(Gl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},className:l,children:a})}function Hg({item:r,level:n,columns:i,nameKey:s,iconComponent:o,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:x,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:C}){const k=l.has(r.id),_=(r.children?.length??0)>0,S=24*n,D="inline"===m,P=v===r.id||p?.has(r.id)&&v&&p?.has(v),E=x===r.id&&v!==r.id,T=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w};return a(t,{children:[a(Wl,{className:Ki(d&&"cursor-pointer",D&&"group",P&&"opacity-40",E&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(Wg,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[h&&e(ao,{checked:T,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:"⠿"}),_?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(k?A:z,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),o??e(qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"truncate",children:String(r[s]??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],s=t.render?t.render(r,n):null!=i?String(i):"—";return e(Wg,{...I,className:Ki("text-center",t.className),children:t.hoverContent?a(Fu,{openDelay:200,children:[e(Uu,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:s})}),e(ju,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):s},String(t.key))}),u&&e(Wg,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:Ki("flex items-center justify-end gap-1",D&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),_&&k&&r.children.map(a=>e(Hg,{item:a,level:n+1,columns:i,nameKey:s,iconComponent:o,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:x,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:C},a.id))]})}function Gg({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i,label:s}){return a("div",{className:Ki("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(Ta,{className:"h-4 w-4"}),s??"Tornar Raiz"]})}function Yg({data:t,columns:r,nameKey:s,nameHeader:l="Nome",iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="",rowActionsVariant:g="default",isLoading:v,emptyMessage:x="Nenhum registro encontrado.",className:b,enableSelection:y,selectedIds:N,onSelectItem:w,onSelectAll:C,isAllSelected:k,enableRowDrag:_,onMoveNode:S,onMoveNodes:A,rootDropLabel:D,actionsWidth:P=20,nameMinWidth:E=200}){const[T,I]=i(null),[M,R]=i(null),[L,z]=i(!1),[F,U]=i(1),j=d(null),O=d([]),B=d(null),$=n.useMemo(()=>new Set(N??[]),[N]),V=n.useMemo(()=>{if(!T||!t)return new Set;const e=O.current.length>0?O.current:[T],a=function(e,a){const t=new Set;for(const r of a)qg(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[T,t]),q=d(V);q.current=V;const W=o(()=>{j.current=null,O.current=[],B.current=null,I(null),R(null),z(!1),U(1)},[]),H=o((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),G=o((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=o((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",q.current.has(e)?R(null):(B.current=e,R(e))},[]),K=o((e,a)=>{a.preventDefault(),a.stopPropagation();const t=q.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=o(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=o(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",z(!0)},[]),J=o(e=>{_&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[_]),Z=o(e=>{if(!_)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]);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(qe,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:x})]});const ee=null!==T;return a("div",{className:Ki("border rounded-lg overflow-hidden relative",b),onDragOver:J,onDrop:Z,onDragLeave:_?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(R(null),z(!1))}:void 0,children:[_&&ee&&e(Gg,{onDrop:Q,isDragOver:L,onDragOver:X,onDragLeave:()=>z(!1),label:D}),a(Bl,{children:[e($l,{children:a(Wl,{children:[e(Hl,{className:"text-left",style:{minWidth:E},children:a("div",{className:"flex items-center gap-2",children:[y&&e(ao,{checked:k??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(Hl,{className:Ki("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(Hl,{className:"text-right",style:{width:P},children:f})]})}),e(Vl,{children:t.map(a=>e(Hg,{item:a,level:0,columns:r,nameKey:s,iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:y,selectedIds:$,onSelectItem:w,enableRowDrag:_,draggedId:T,dragOverId:M,onDragStartCell:G,onDragEndCell:W,onDragOverCell:Y,onDropCell:K,dragCount:F},a.id))})]})]})}function Kg(e){const a=pt();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 Qg(e,a){const t=Kg({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Xg=n.memo(({variant:r="card",className:i="",selectedUnit:o,onUnitChange:l})=>{const{user:c,companies:d,alias:u,isAuthenticated:m,logout:h,switchUnit:p}=zl(),{role:f}=Xd(),g=f?.name||null,v=d?.[0]||null,x=u?d?.find(e=>e.alias===u):v,b=d||[],y=o||x||v||v,N=s(()=>{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]),w=s(()=>{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]),k=n.useMemo(()=>{if(!b?.length)return[];const e=new Map;b.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===y?.alias),r=a.filter(e=>e.alias!==y?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[b,y?.alias]);if(!m||!c)return null;return"dropdown"===r?a(co,{children:[e(uo,{asChild:!0,children:e(es,{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:y?.name||"N/A"})]}),a(cu,{className:"w-8 h-8 border border-primary-foreground/30",children:[N&&e(du,{src:N,alt:c.name||"Foto do usuário"}),e(uu,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:w||e(qe,{className:"h-4 w-4"})})]}),e(A,{className:"h-4 w-4"})]})})}),a(xo,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(po,{children:[a(go,{children:[e(Je,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(vo,{children:k.map(t=>a(bo,{onClick:()=>C(t),className:t.alias===y?.alias?"bg-muted":"",children:[e(aa,{className:"mr-2 h-4 w-4"}),t.name,t.alias===y?.alias&&e(no,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(Co,{}),a(bo,{onClick:h,children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(is,{className:i,children:[e(ss,{children:e(os,{className:"text-lg",children:"Informações do Usuário"})}),a(cs,{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(cu,{className:"w-10 h-10",children:[N&&e(du,{src:N,alt:c.name||"Foto do usuário"}),e(uu,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:w||e(qe,{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: ",y?.name||"N/A"]})]})]}),y&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(aa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:y.name})]})}),k.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",k.length]}),a("div",{className:"flex flex-wrap gap-1",children:[k.slice(0,3).map(a=>e(no,{variant:a.alias===y?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>C(a),children:a.name},a.alias)),k.length>3&&a(no,{variant:"outline",className:"text-xs",children:["+",k.length-3]})]})]})]}),{}),e(us,{}),a(es,{variant:"outline",onClick:h,size:"sm",className:"w-full",children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Jg=l({});function Zg({children:a,config:t}){const r=s(()=>{const e=wr(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Jg.Provider,{value:r,children:a})}function ev(){return c(Jg)}function av(){const e=ft(),{navigation:a}=ev();return tv(a,e.pathname)}function tv(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 rv(e,a){const[t,r]=i(e),n=d(),s=o(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return u(()=>(s(),n.current=setTimeout(()=>{r(e)},a),s),[e,a,s]),[t,s]}function nv({appName:r}){const[n,s]=i(!1);return a(t,{children:[a("div",{className:"flex items-center justify-between w-[258px]",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:zr.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/80 hover:text-primary-foreground/60 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(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return a(t,{children:[s," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(r)})})]}),e(Zd,{open:n,onOpenChange:s})]})}const iv=m(function({actions:t}){const r=ft(),n=pt(),{navigation:s,appName:l}=ev(),c=tv(s,r.pathname),{metadata:d,headerActions:m}=xd(),{setOpenMobile:h}=Vm(),{companies:p,alias:f,isSearchVisible:g,clearSearch:v,refreshData:x,switchUnit:b}=zl(),y=f?p?.find(e=>e.alias===f)||p?.[0]||null:p?.[0]||null,[N,w]=mt(),C=o(e=>{const{pathname:a,search:t,hash:i}=r;if(f){const r=a.split("/"),s=r.indexOf(f);if(s>=0)return r[s]=e.alias,void n(r.join("/")+t+i)}b(e)},[f,r,n,b]),[k,_]=i(()=>N.get("search")||""),[A,D]=rv(k,_r.debounceDelay);u(()=>{if(!g)return;const e=new URLSearchParams(N);A?(e.set("search",A),e.set("page","1")):e.delete("search"),w(e)},[A,w,g]);const P=s?.find(e=>e.path===r.pathname)||s?.find(e=>r.pathname.startsWith(e.path+"/")),E=d.title||c,T=d.subtitle||P?.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(es,{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(Ia,{size:20})}),e("div",{className:"hidden md:flex items-center flex-shrink-0",children:e(nv,{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(z,{className:"h-3 w-3"}),t.href?e(vt,{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:E})}),e("div",{className:"text-sm text-primary-foreground/70 truncate",children:T})]}),g&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(ts,{placeholder:"Pesquisar",value:k,onChange:e=>(e=>{_(e)})(e.target.value),className:"w-full pl-10 pr-8"}),k&&e(es,{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:()=>{D(),_("");const e=new URLSearchParams(N);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(es,{variant:"outline",size:"sm",onClick:x,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(es,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Gi(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e(cp,{}),e("div",{className:"text-sm",children:e(Xg,{variant:"dropdown",selectedUnit:y,onUnitChange:C})})]})]})})}),sv=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>lt({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function ov({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:s}){const{actions:o,triggerLabel:l="Criar",triggerIcon:c=Y,variant:d="button"}=r;if(!o||0===o.length)return null;if("split-button"===d){const t=o[0],r=t.icon||c,l=o.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(es,{onClick:t.onClick,disabled:i||t.disabled,className:Ki("justify-center px-2 w-full",s),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(So,{children:[e(Ao,{asChild:!0,children:n}),e(Do,{side:"right",children:e("p",{children:t.label})})]})}return e(Xh,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:Ki("w-full",s),menuAlign:"start"})}const u=(r,i,s=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&s&&e(A,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||c,l=i||t.disabled,d=e(es,{onClick:t.onClick,disabled:l,className:Ki("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(So,{children:[e(Ao,{asChild:!0,children:d}),e(Do,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(es,{disabled:i,className:Ki("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(co,{children:[e(uo,{asChild:!0,children:n?a(So,{children:[e(Ao,{asChild:!0,children:m}),e(Do,{side:"right",children:e("p",{children:l})})]}):m}),e(xo,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(bo,{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 lv="forlogic-sidebar-pinned",cv=()=>{try{const e=localStorage.getItem(lv);return!!e&&JSON.parse(e)}catch{return!1}};function dv({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:s,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","290px"))},[c,l]);const g=o(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),s?.(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,s]),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 uv=l(void 0);function mv({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=o(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=o(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=o(e=>{l(e)},[]),m=s(()=>t.size>0||n,[t,n]),h=s(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(uv.Provider,{value:h,children:a})}function hv(){const e=c(uv);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function pv(){const{hasOpenModal:e}=hv();return e}function fv({config:t,customContent:r,resizable:n=!1,minWidth:s=224,maxWidth:l=384}={}){const{open:c,setOpen:d,setOpenMobile:m}=Vm(),h=ft(),{alias:p,user:f}=zl(),{appName:g}=ev(),{hasOpenModal:v}=hv(),[x,b]=i(cv),y=Ol(),N=o(()=>{y&&m(!1)},[y,m]),w=n?dv({minWidth:s,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;u(()=>{d(!!x)},[x,d]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(Wm,{collapsible:"icon",className:Ki("app-sidebar bg-background border-r border-border flex flex-col",c?"px-3":"px-1.5"),style:w&&c?{width:`${w.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(_o,{children:e(ov,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(Zm,{className:Ki(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(eh,{className:"p-0",children:e(rh,{children:e(nh,{className:"gap-1",children:e(_o,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:s=!0,isLoading:o}=sv({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!s,d=o?E:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e(Md,{defaultOpen:!0,className:"group/collapsible",children:a(ih,{children:[e(Rd,{asChild:!0,children:e(oh,{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(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Ld,{children:e(uh,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(ih,{children:a(So,{children:[e(Ao,{asChild:!0,children:e("div",{className:Ki("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(Do,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(ih,{children:l||o?a(So,{children:[e(Ao,{asChild:!0,children:c?e(oh,{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 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(Do,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):c?e(oh,{asChild:!0,isActive:C(t.path),size:"default",children:a(vt,{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(So,{children:[e(Ao,{asChild:!0,children:e(vt,{to:t.path,onClick:N,className:Ki("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(Do,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),!y&&e("div",{className:Ki("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:a(So,{children:[e(Ao,{asChild:!0,children:e("button",{onClick:()=>{const e=!x;b(e),(e=>{try{localStorage.setItem(lv,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?Ee:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Do,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})}),n&&w&&c&&e("div",{ref:w.dragRef,onMouseDown:w.handleMouseDown,className:Ki("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",w.isDragging&&"bg-primary/40")})]})}const gv=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=s(()=>r||e(fv,{config:n}),[r,n]),c=s(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),m=d(null),h=d(null),p=o(()=>{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(Zg,{config:n,children:e(vd,{children:e(qm,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"flex flex-col h-screen w-full overflow-hidden",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:e(iv,{})}),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 min-h-0 overflow-y-auto bg-muted/30",children:t})})]})]})})})})});function vv({open:r,appName:n}){const[s,o]=i(!1);return a(t,{children:[e(Qm,{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:()=>o(!0),children:e("img",{src:zr.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:()=>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(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return a(t,{children:[s," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(A,{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:()=>o(!0),children:e("img",{src:zr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(Zd,{open:s,onOpenChange:o})]})}function xv({title:t,subtitle:r,children:n,className:i,hasHeader:s=!0}){const o=t||r;return a("div",{className:Ki("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[s&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:Ki("p-6",!s&&o&&"pt-4"),children:n})]})}function bv({breadcrumbs:t,children:n,className:i}){return a("div",{className:Ki("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(mu,{className:"mb-4",children:e(hu,{children:t.map((n,i)=>{const s=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(vu,{}),e(pu,{children:s||!n.href?e(gu,{children:n.label}):n.asChild&&n.children?e(fu,{asChild:!0,children:n.children}):e(fu,{asChild:!0,children:e(vt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const yv=(e={})=>{const{enabled:a=!0}=e,{alias:t}=zl();return lt({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=pl(),{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(!vl.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Nv({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:s,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),x=d(0),b=o(e=>c[e]??a,[c,a]),y=o((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,x.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,x.current+a));m(e=>{const a={...e,[f]:n};return s?.(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,s]),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=o(()=>{m({}),n&&localStorage.removeItem(n),s?.({})},[n,s]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:y,resetHeights:N,getRowHeight:b}}function wv(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,x=0===c,b=c===v-1,y=a[c],N=v>1?(c+1)/v*100:100,w=o(()=>!y?.canProceed||y.canProceed(),[y]),C=s(()=>w(),[w,u]),k=s(()=>!x&&!y?.disableBack,[x,y]),_=o(e=>{m(a=>({...a,...e}))},[]),S=o((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=o(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),D=o(async()=>{if(w()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[w,f,u,n]),P=o(async()=>{w()&&!h&&(b?await D():d(e=>Math.min(e+1,v-1)))},[w,h,b,v,D]),E=o(()=>{k&&!h&&d(e=>Math.max(e-1,0))},[k,h]),T=o(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=o(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:y,data:u,isFirstStep:x,isLastStep:b,isLoading:h,isCompleting:f,next:P,back:E,goTo:T,canProceed:C,canGoBack:k,setData:_,updateField:S,reset:A,complete:D,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const Cv=()=>{const{locale:e,timezone:a}=Pd(),t=Ti;return{formatDatetime:r=>qi(r,t,a,e),formatDate:t=>Wi(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class kv{static async sendEmail(e){const a=pl(),{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 _v=kv;function Sv({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:x=[],isLoading:b}=Vc({enabled:t}),y=s(()=>{let e=[...x];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},[x,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},w=1===m.length,C=m.length>0;return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"max-w-2xl",variant:"form",children:[e(Es,{showSeparator:!0,children:a(Ms,{className:"flex items-center gap-2",children:[e(Sa,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(Ts,{children:[a("div",{className:"relative mb-4",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Ho,{className:"h-[400px] pr-4",children:b?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e($o,{className:"h-16 w-full"},t))}):0===y.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(Sa,{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:y.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:Ki("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(ao,{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(Ma,{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(Is,{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)"]})}),w&&l&&a(es,{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(Ma,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(es,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Ra,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function Av({place:t,level:r=0,manageAccessConfig:n}){const[s,o]=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(Md,{open:s,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[d?a(Rd,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:Ki("h-4 w-4 transition-transform shrink-0",s&&"rotate-90")}),e(aa,{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(aa,{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(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(no,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e($g,{customActions:[{label:"Gerenciar Acessos",icon:Ve,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Ld,{children:t.subPlaces.map(a=>e(Av,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(us,{}),n&&e(Sv,{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 Dv({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(Av,{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(aa,{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 Pv=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=xl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=cl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status}`);throw e.status=s.status,e}return s.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 xl.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 dl.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return dl.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Ev(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 Tv(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 Iv(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Mv(){const{alias:e,isAuthenticated:a}=zl(),t=cl.getAccessToken(),{data:r=[]}=Vc({enabled:!0});return lt({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=pl(),{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 s={};r.forEach(e=>{s[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:s[e.id_user]?.name||"[Usuário inativo]",email:s[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>s[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=s[e],t=n.filter(a=>a.id_leader===e);o.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>s[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),Tv(o)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const Rv="common";function Lv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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 Ov(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(Rv).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]}),C.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{C.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function zv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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(Rv).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 Ov(t,e,c.id_user,a.id_leader)}const s=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(Rv).from("leaders").insert(s).select();if(l)throw l;return o},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{C.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Fv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(Rv).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 Ov(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:s}=await t.schema(Rv).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(s)throw s;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{C.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function Uv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(Rv).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{C.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function jv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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),s=await Promise.all([t.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:o,error:l},{data:c,error:d}]=s;if(l)throw l;if(d)throw d;const u=o||[],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 Ov(t,e,r.id_user,a,r.id);for(const y of v){if(y.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Ov(t,e,y.id_user,a)}const x=[];if(p.length){const a=p.map(e=>e.id);x.push(t.schema(Rv).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);x.push(t.schema(Rv).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}));x.push(t.schema(Rv).from("leaders").insert(r))}const b=(await Promise.all(x)).find(e=>e?.error);if(b?.error)throw b.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{C.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Ov(e,a,t,r,n){const{data:i,error:s}=await e.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(s)throw s;const o=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=o.find(e=>e.id_user===c);c=e?.id_leader||null}}var Bv=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,s=r.path.join(".");if(!t[s])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[s]={message:o.message,type:o.code}}else t[s]={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[s].types,c=l&&l[r.code];t[s]=Ka(s,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},$v=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,s){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&gr({},i),{errors:{},values:t.raw?r:e}})}catch(l){return s(l)}return o&&o.then?o.then(void 0,s):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:vr(Bv(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(s){return Promise.reject(s)}}};const Vv=fr.object({id_leader:fr.string().nullable(),id_users:fr.array(fr.string()).min(1,"Selecione pelo menos um liderado")}),qv=fr.object({id_leader:fr.string().nullable(),id_users:fr.array(fr.string())});function Wv({value:t,onChange:r,excludeUserIds:n=[],error:s}){const{data:o=[],isLoading:l}=Vc(),[c,m]=i(""),h=d(null),p=d(0),f=o.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||"",s=a.userName||a.userEmail||"";return i.localeCompare(s)});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(E,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(ts,{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(ao,{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(ns,{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)"]}),s&&e("p",{className:"text-sm text-destructive",children:s})]})}function Hv({leader:r,prefilledLeaderId:n,onSuccess:s}){const{alias:o}=zl(),l=!!r,c=r?.id.startsWith("virtual-"),d=zv(),m=Lv(),h=Fv(),p=jv(),f=Uv(),{data:g=[]}=Mv(),{data:v=[]}=Vc(),[x,b]=i(""),y=Iv(g).map(e=>e.id_user),N=l?Iv(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],w=Qa({resolver:$v(l?qv:Vv),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});u(()=>{if(r){const e=Iv(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);w.reset({id_leader:r.id_leader||null,id_users:e})}else n?w.reset({id_leader:n,id_users:[]}):w.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=d.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=w.watch("id_leader"),_=w.watch("id_users"),S=l?[r.id_user,...y.filter(e=>e!==r.id_user&&!_.includes(e)&&!N.includes(e))]:[k,...y.filter(e=>!_.includes(e))].filter(Boolean);return a("form",{onSubmit:w.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})}s?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(ns,{children:"Líder"}),e(ts,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(ns,{children:"Superior Imediato"}),a(Ws,{value:k||"none",onValueChange:e=>w.setValue("id_leader","none"===e?null:e),children:[e(Ys,{children:e(Gs,{placeholder:"Selecione..."})}),a(Xs,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(ts,{placeholder:"Buscar superior...",value:x,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Ho,{className:"h-[200px]",children:[e(Zs,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!_.includes(e.userId),t=!x||e.userName?.toLowerCase().includes(x.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(Zs,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),w.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:w.formState.errors.id_leader.message})]}),a("div",{children:[e(ns,{children:"Subordinados *"}),e(Wv,{value:_,onChange:e=>w.setValue("id_users",e),excludeUserIds:S,error:w.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(es,{type:"submit",disabled:C||!l&&0===_.length,children:C&&!f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!k&&0===_.length&&a(ms,{children:[e(hs,{asChild:!0,children:e(es,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(q,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(gs,{children:[a(vs,{children:[e(bs,{children:"Confirmar remoção"}),e(ys,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(xs,{children:[e(ws,{children:"Cancelar"}),e(Ns,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),s?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function Gv({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:s}){return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{variant:"form",className:"sm:max-w-[500px]",children:[e(Es,{showSeparator:!0,children:e(Ms,{children:s})}),e(Ts,{children:e(Hv,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Yv="leadership-expanded-nodes",Kv=(e,a)=>{try{localStorage.setItem(`${Yv}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Qv({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c,columns:d,nameHeader:m="Líder",rootDropLabel:h="Tornar Líder Raiz"}={}){const{alias:p}=zl(),{data:f,isLoading:g,error:v,refetch:x}=Mv(),b=Fv(),y=Lv(),[N,w]=i(()=>p?(e=>{try{const a=localStorage.getItem(`${Yv}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(p):new Set),[C,k]=i([]),[_,S]=i(new Set),[D,P]=i(!0),[E,T]=i(!1),[I,M]=i(),[R,L]=i(null),F=s(()=>f?Iv(f):[],[f]),U=s(()=>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(`${Yv}-${p}`)){const e=f.map(e=>e.id),a=new Set(e);w(a),Kv(p,a)}}},[f,p]);const B=o(e=>{w(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),p&&Kv(p,t),t})},[p]),$=o(()=>{if(O){const e=new Set;w(e),p&&Kv(p,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));w(e),p&&Kv(p,e)}},[O,F,p]),V=o(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),q=o(()=>{k(j?[]:U)},[j,U]),H=o(e=>{S(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),G=o(e=>F.find(a=>a.id===e),[F]),K=o((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?G(a):null;n(t.id,e?.id_user||null)}else y.mutate({id_user:t.id,id_leader:a&&G(a)?.id_user||null});return}const i=G(e);if(!i)return;const s=a?G(a):null;b.mutate({id:i.id,id_leader:s?.id_user||null})},[l,r,n,G,b,y]),Q=o((e,a)=>{c?c(e,a):(e.forEach(e=>K(e,a)),k([]))},[c,K]),X=o(e=>{M(e),L(null),T(!0)},[]),J=o(()=>{M(void 0),L(null),T(!0)},[]),Z=o(()=>{T(!1),M(void 0),L(null)},[]),ee=o((e,a)=>{const t=_.has(e)&&_.size>1?Array.from(_):[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"},[_]),ae=s(()=>[{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(qe,{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(es,{onClick:()=>x(),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(es,{size:"sm",onClick:J,children:[e(Y,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(es,{size:"sm",variant:"outline",onClick:$,children:a(t,O?{children:[e(A,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(z,{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(Sa,{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(Yg,{data:f||[],columns:te,nameKey:"name",nameHeader:m,expandedIds:N,onToggleExpand:B,iconComponent:e(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:V,onSelectAll:q,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(es,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>X(a),children:e(W,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>P(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(D?A:z,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Ra,{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,")"]}),_.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",_.size," selecionado",_.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),D&&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:Ki("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",_.has(t.id)&&"bg-primary/5"),children:[e(ao,{checked:_.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(qe,{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(Gv,{open:E,onOpenChange:Z,leader:I,prefilledLeaderId:R,title:I?"Editar Nome":R?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${p}`)]})}function Xv(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:s,onSuccess:o,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...s,...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 C.success("Sucesso",{description:"Arquivo enviado com sucesso"}),o?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw C.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 C.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),C.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw C.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Jv(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 Zv(e,a){const t=Jv(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function ex(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function ax(e,a){const t=ex(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function tx(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function rx(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function nx(e,a,t){switch(a||rx(e)){case"youtube":return Zv(e,t);case"vimeo":return ax(e,t);default:return e}}function ix({value:r,onChange:n,onSubmit:o,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:x}=Xv({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:b,uploading:y}=Xv({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=s(()=>rx(h.videoUrl||tx(h.embedCode)||""),[h.videoUrl,h.embedCode]),w=(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(ns,{children:"Tipo de entrada"}),a(Ws,{value:h.inputType||"url",onValueChange:e=>w("inputType",e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"url",children:"URL"}),e(Zs,{value:"upload",children:"Upload de arquivo"}),e(Zs,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(ns,{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(es,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:x,children:a(t,x?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{children:"Código embed"}),e(to,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>w("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(ns,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(ts,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>w("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 b(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(es,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:a(t,y?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{htmlFor:"title",children:"Título"}),e(ts,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>w("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e(ao,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>w("autoplay",!0===e)}),e(ns,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(ao,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>w("controls",!0===e)}),e(ns,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||tx(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?Zv(t,h.autoplay):ax(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(es,{variant:"outline",onClick:l,children:"Cancelar"}),e(es,{onClick:()=>{h.videoUrl||h.embedCode?o(h):C.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function sx({content:t,className:r="",style:n}){const i=t.videoUrl||tx(t.embedCode)||"";if(!i)return null;const s=rx(i);return e(is,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(cs,{className:"p-0",children:["file"===s?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"===s?Zv(i,t.autoplay):ax(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 ox({value:r,onChange:n,onSubmit:s,onCancel:o,uploadFunction:l,deleteFunction:c,uploadOptions:u}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=d(null),{upload:f,uploading:g}=Xv({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(ns,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(ts,{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(es,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{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(ns,{htmlFor:"caption",children:"Legenda"}),e(to,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"alt",children:"Texto Alternativo"}),e(ts,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Alinhamento"}),a(Ws,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"left",children:"Esquerda"}),e(Zs,{value:"center",children:"Centro"}),e(Zs,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"width",children:"Largura"}),e(ts,{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(ns,{htmlFor:"height",children:"Altura"}),e(ts,{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(ao,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(ns,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(es,{variant:"outline",onClick:o,children:"Cancelar"}),e(es,{onClick:()=>{m.imageUrl?s(m):C.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function lx({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 cx(e,a){return e/a}function dx(e,a,t,r){const n=cx(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 ux(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 mx(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 hx(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function px(){const{alias:e}=zl(),[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=pl(),{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 s=o(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=pl(),{data:i,error:s}=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(s)throw s;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:s}}const fx=import.meta.env.VITE_SUPABASE_URL,gx=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function vx(e,a,t){const r=cl.getSupabaseToken(),n={"Content-Type":"application/json",apikey:gx};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${fx}/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 xx={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await vx(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 vx(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let bx=null;function yx(){return window.Clicksign?Promise.resolve():bx||(bx=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)}),bx)}const Nx="clicksign-container";function wx({signerId:t,environment:r="sandbox",onSign:n,onError:s,onClose:o}){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),yx().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(Nx),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Nx);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),s?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),s?.(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(E,{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:Nx,style:{height:"600px"}})]})}function Cx({documentKey:t,signerEmail:r,signerName:n,keySigner:s,environment:l,onSign:c,onError:m}){const h=d(null),[p,f]=i("loading"),[g,v]=i(null),x="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",b=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return s&&e.set("key_signer",s),`${x}/${t}?${e.toString()}`})(),y=o(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",y,!1),()=>{window.removeEventListener("message",y,!1)}),[y]);const N=o(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(ud,{variant:"danger",className:"my-4",children:[e(md,{children:"Erro ao carregar documento"}),e(hd,{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(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:b,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function kx({file:t,onDocumentSigned:r,onError:n,showEventLog:s=!1}){const{user:l,alias:c}=zl(),{config:m,isLoading:h}=px(),{t:p}=tt(),[f,g]=i(null),[v,x]=i(!1),[b,y]=i(null),[N,w]=i("sandbox"),[k,_]=i("clicksign"),[S,A]=i(null),[D,P]=i(null),[T,I]=i(!1),[M,R]=i(0),[L,z]=i(!1),[F,U]=i([]),j=d(null),O=d(null),B=o(e=>{s&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[s]),$=o(async e=>{if(g(e),y(null),A(null),P(null),B(`Arquivo selecionado: ${e.name}`),c&&l){x(!0);try{const a=m?.provider??"clicksign";_(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 xx.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}),w(i.environment),_(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),y(i.document_id),C.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)),y(i.signer_id),C.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),C.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"),C.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),C.error(t)),n?.(e)}finally{x(!1)}}},[c,l,B,n,m]);u(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,$(t))},[t,c,l,h,$]);const V=o(async()=>{if(!S||!c)return;I(!0),R(0),z(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){R(a),B(`Tentativa ${a}/6...`);try{const e=await xx.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:k});if(e.download_url)return B("Documento assinado disponível para download"),P(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),z(!0)},[S,c,B,k]),q=o(async()=>{B("Documento assinado com sucesso!"),C.success(p("sign_signed_success","Documento assinado com sucesso!")),y(null),S&&c&&(r?.({success:!0,provider:k,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:b||"",environment:N}),await V())},[B,r,S,b,c,N,k,V]);if(!c)return e(is,{className:"border-amber-200 bg-amber-50",children:e(cs,{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"===k?"D4Sign":"Clicksign",H=()=>s&&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&&!b&&(D||T||L)?a("div",{className:"space-y-4",children:[e(is,{className:"border-green-200 bg-green-50",children:a(cs,{className:"flex flex-col items-center gap-4 py-8",children:[e(Da,{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})]}),T?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(E,{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}...`)})]}):D?e(es,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):L?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(es,{variant:"secondary",className:"gap-2",onClick:V,children:[e(Je,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):b?a("div",{className:"space-y-4",children:["d4sign"===k?e(Cx,{documentKey:b,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:q,onError:n}):e(wx,{signerId:b,environment:N,onSign:q,onError:n}),e(H,{})]}):t&&(v||h)?e(is,{children:a(cs,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{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):C.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(is,v?{children:a(cs,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{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(cs,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(we,{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 _x({onSaved:t}){const{config:r,isLoading:n,saveConfig:s}=px(),{t:o}=tt(),[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(E,{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:o("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(U,{className:"h-4 w-4"}),e("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(is,{children:[e(ss,{children:e(os,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e(cs,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await s(l.trim(),d),C.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){C.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else C.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"sign-api-key",children:"API Key"}),e(ts,{id:"sign-api-key",type:"password",placeholder:o("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(ns,{children:o("sign_environment","Ambiente")}),a(Ws,{value:d,onValueChange:e=>m(e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"sandbox",children:"Sandbox (Testes)"}),e(Zs,{value:"production",children:"Produção"})]})]})]}),a(es,{type:"submit",disabled:h,children:[h&&e(E,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})}var Sx,Ax,Dx,Px,Ex,Tx,Ix,Mx,Rx,Lx;(Ax=Sx||(Sx={}))[Ax.waitingStart=1]="waitingStart",Ax[Ax.running=2]="running",Ax[Ax.effectivenessCheck=3]="effectivenessCheck",Ax[Ax.done=4]="done",Ax[Ax.suspended=5]="suspended",Ax[Ax.canceled=6]="canceled",(Px=Dx||(Dx={}))[Px.low=0]="low",Px[Px.medium=1]="medium",Px[Px.high=2]="high",(Tx=Ex||(Ex={}))[Tx.plan=2]="plan",Tx[Tx.occurrence=3]="occurrence",Tx[Tx.risk=4]="risk",Tx[Tx.decisions=5]="decisions",Tx[Tx.audit=6]="audit",Tx[Tx.strategyExtension=7]="strategyExtension",Tx[Tx.standardization=8]="standardization",Tx[Tx.supplier=9]="supplier",Tx[Tx.auditItems=10]="auditItems",(Mx=Ix||(Ix={}))[Mx.currentProgress=1]="currentProgress",Mx[Mx.cumulativeProgress=2]="cumulativeProgress",(Lx=Rx||(Rx={})).uploading="uploading",Lx.waiting="waiting",Lx.done="done",Lx.error="error",Lx.canceled="canceled",Lx.duplicateItem="duplicateItem";const zx={[Sx.waitingStart]:"#D6D6D6",[Sx.running]:"#DAE9F4",[Sx.effectivenessCheck]:"#1B75BB29",[Sx.done]:"#DDEECA",[Sx.suspended]:"#FFF2D6",[Sx.canceled]:"#F4433629"},Fx={[Sx.waitingStart]:"#666666",[Sx.running]:"#1B75BB",[Sx.effectivenessCheck]:"#1B75BB",[Sx.done]:"#4CAF50",[Sx.suspended]:"#FF9800",[Sx.canceled]:"#F44336"},Ux={[Sx.waitingStart]:"waiting-start",[Sx.running]:"running",[Sx.effectivenessCheck]:"effectiveness-check",[Sx.done]:"done",[Sx.suspended]:"suspended",[Sx.canceled]:"canceled"},jx={[Sx.waitingStart]:"Aguardando início",[Sx.running]:"Em andamento",[Sx.effectivenessCheck]:"Verificação de eficácia",[Sx.done]:"Concluída",[Sx.suspended]:"Suspensa",[Sx.canceled]:"Cancelada"},Ox=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}],Bx=[{id:Dx.low,label:"Baixa",color:"#4CAF50"},{id:Dx.medium,label:"Média",color:"#FF9800"},{id:Dx.high,label:"Alta",color:"#F44336"}],$x=[Sx.done,Sx.canceled],Vx=[Sx.waitingStart,Sx.running,Sx.effectivenessCheck,Sx.suspended];function qx(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:s,onDelete:l,onChangeStatus:c}=e,[d,m]=i({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});u(()=>{a&&m(e=>({...e,formData:a,isFormDisabled:r?.disableFields||$x.includes(a.statusId)}))},[a,r?.disableFields]),u(()=>{m(a=>({...a,isLoading:e.isLoading||!1}))},[e.isLoading]);const h=o((e,a)=>{m(t=>({...t,formData:{...t.formData,[e]:a}}))},[]),p=o(e=>{m(a=>({...a,activeTab:e}))},[]),f=o(async()=>{if(n){m(e=>({...e,isSaving:!0}));try{await n(d.formData)}finally{m(e=>({...e,isSaving:!1}))}}},[n,d.formData]),g=o(async e=>{if(c&&d.formData.id){m(e=>({...e,isLoading:!0}));try{await c(d.formData.id,e)}finally{m(e=>({...e,isLoading:!1}))}}},[c,d.formData.id]),v=o(async()=>{if(l&&d.formData.id){m(e=>({...e,isLoading:!0}));try{await l(d.formData.id)}finally{m(e=>({...e,isLoading:!1}))}}},[l,d.formData.id]);return{formData:d.formData,isLoading:d.isLoading,isSaving:d.isSaving,activeTab:d.activeTab,isFormDisabled:d.isFormDisabled,updateField:h,setActiveTab:p,save:f,changeStatus:g,remove:v,cancel:s}}function Wx({status:a,labels:t,className:r}){const n=t?.[a]||jx[a]||"",i=zx[a]||"#D6D6D6",s=Fx[a]||"#666666";return e("span",{className:Ki("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",r),style:{backgroundColor:i,color:s},children:n})}function Hx({formData:t,updateField:r,disabled:i=!1,users:s=[],places:o=[],actionTypes:l,causes:c=[],parentActions:d=[],config:u}){const m=u?.requiredFields,h=l||Ox,p=e=>{if(u?.hiddenFields?.includes(e))return!1;if(u?.visibleFields&&u.visibleFields.length>0)return u.visibleFields.includes(e);const a=`${e}Visible`;return!m||!(a in m)||!1!==m[a]},f=e=>m?!!m[e]:"name"===e,g=n.useMemo(()=>{if(t.startDate&&t.endDate){const e=new Date(t.startDate),a=new Date(t.endDate).getTime()-e.getTime();return Math.max(0,Math.ceil(a/864e5))}return t.duration||0},[t.startDate,t.endDate,t.duration]);return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),e(ts,{value:t.name||"",onChange:e=>r("name",e.target.value),maxLength:500,disabled:i,placeholder:"Nome do plano de ação"})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("responsibleWho")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),a(Ws,{value:t.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o responsável"})}),e(Xs,{children:s.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),p("checkerWho")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),a(Ws,{value:t.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o verificador"})}),e(Xs,{children:s.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("place")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),a(Ws,{value:t.placeId||"",onValueChange:e=>r("placeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o local"})}),e(Xs,{children:Gx(o).map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),p("planType")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),a(Ws,{value:t.typeId||"",onValueChange:e=>r("typeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o tipo"})}),e(Xs,{children:h.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("priority")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),a(Ws,{value:t.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a prioridade"})}),e(Xs,{children:Bx.map(t=>e(Zs,{value:t.id.toString(),children:a("span",{className:"flex items-center gap-2",children:[e("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),d.length>0&&a("div",{className:"space-y-2",children:[e(ns,{children:"Pertence a"}),a(Ws,{value:t.parentId||"",onValueChange:e=>r("parentId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a ação pai"})}),e(Xs,{children:d.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[p("startDate")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),e(Cu,{date:t.startDate?new Date(t.startDate):void 0,onDateChange:e=>r("startDate",e||null),disabled:i,placeholder:"Selecione a data"})]}),p("endDate")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),e(Cu,{date:t.endDate?new Date(t.endDate):void 0,onDateChange:e=>r("endDate",e||null),disabled:i,placeholder:"Selecione a data",disabledDates:t.startDate?e=>e<new Date(t.startDate):void 0})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Duração (dias)"}),e(ts,{type:"number",value:g,disabled:!0,className:"bg-muted"})]})]}),p("estimatedCost")&&a("div",{className:"space-y-2 max-w-xs",children:[e(ns,{className:Ki(f("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),a("div",{className:"relative",children:[e("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),e(ts,{type:"number",min:0,step:.01,value:t.estimatedCost||"",onChange:e=>r("estimatedCost",Number(e.target.value)),disabled:i,className:"pl-9",placeholder:"0,00"})]})]}),p("cause")&&c.length>0&&a("div",{className:"space-y-2",children:[e(ns,{children:"Causa"}),a(Ws,{value:t.causeId||"",onValueChange:e=>r("causeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a causa"})}),e(Xs,{children:c.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]}),p("description")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),e(to,{value:t.description||"",onChange:e=>r("description",e.target.value),maxLength:4e3,disabled:i,rows:4,placeholder:"Descreva o plano de ação"})]}),p("justification")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),e(to,{value:t.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:i,rows:4,placeholder:"Justificativa do plano de ação"})]})]})}function Gx(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...Gx(r.children,a+1));return t}function Yx(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[s,l]=i(!1),[c,d]=i(null),u=!!a&&Vx.includes(a.status),m=o(async e=>{if(t&&a){l(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{l(!1)}}},[t,a]),h=o(async e=>{if(r){l(!0);try{await r(e)}finally{l(!1),d(null)}}},[r]),p=o(async e=>{if(n){l(!0);try{await n(e)}finally{l(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:s,editingReport:c,setEditingReport:d,reportProgress:m,editProgress:h,deleteProgress:p}}function Kx(e){if(!e)return"";let a=(e||"").trim();if(!a)return"00:00";if(a.includes(":")){const e=a.split(":");if(e.length>=2){const a=e[0].replace(/\D/g,""),t=e[1].replace(/\D/g,"");let r=parseInt(a)||0,n=parseInt(t)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}if(a=a.replace(/\D/g,""),!a)return"00:00";let t=0,r=0;return 4===a.length?(t=parseInt(a.substring(0,2))||0,r=parseInt(a.substring(2,4))||0,t+=Math.floor(r/60),r%=60):(t=parseInt(a)||0,r=0),`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function Qx(e){if(null==e)return"00:00";const a=String(e).replace(/\D/g,"");if(a.length<3){let e=parseInt(a)||0;const t=Math.floor(e/60);return e%=60,`${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=a.slice(-2),t=a.slice(0,-2);let r=parseInt(t)||0,n=parseInt(e)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}function Xx(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Jx({open:t,onOpenChange:r,report:s,onSave:o,isSubmitting:l=!1}){const[c,d]=i(s?.percentProgress||0),[u,m]=i(s?.timeProgress||""),[h,p]=i(s?.comments||"");n.useEffect(()=>{s&&(d(s.percentProgress),m(s.timeProgress||""),p(s.comments||""))},[s]);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-md",children:[e(Es,{children:e(Ms,{children:"Editar Progresso"})}),a("div",{className:"space-y-4 py-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Progresso (%)"}),e(ts,{type:"number",min:0,max:100,value:c,onChange:e=>d(Number(e.target.value))})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Tempo gasto (HH:MM)"}),e(ts,{value:u,onChange:e=>m(e.target.value),onBlur:()=>m(Kx(u)||""),placeholder:"00:00"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Comentários"}),e(to,{value:h,onChange:e=>p(e.target.value),rows:3,maxLength:4e3})]})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),e(es,{onClick:()=>{s&&o({...s,percentProgress:c,timeProgress:Kx(u)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function Zx(t){const{progress:r,canReportProgress:n,isSubmitting:s,editingReport:o,setEditingReport:l,reportProgress:c,editProgress:d,deleteProgress:u}=Yx(t),[m,h]=i(""),[p,f]=i(""),[g,v]=i("");if(!r)return e("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const x=Xx(r.percentProgress),b=!m,y=!m&&!p&&!g;return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{className:"flex items-center justify-between text-sm",children:[e("span",{className:"font-medium",children:"Progresso geral"}),a("span",{className:"font-semibold",style:{color:x||void 0},children:[r.percentProgress,"%"]})]}),e(Cm,{value:r.percentProgress,className:"h-3"}),r.timeProgress&&a("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Qx(r.timeProgress)]})]}),n&&a("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e("h4",{className:"text-sm font-medium",children:"Reportar progresso"}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Progresso (%)"}),e(ts,{type:"number",min:0,max:100,value:m,onChange:e=>h(e.target.value),placeholder:"0"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Tempo gasto (HH:MM)"}),e(ts,{value:p,onChange:e=>f(e.target.value),onBlur:()=>f(Kx(p)||""),placeholder:"00:00"})]})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Comentários"}),e(to,{value:g,onChange:e=>v(e.target.value),rows:3,maxLength:4e3,placeholder:"Adicione um comentário sobre o progresso"})]}),a("div",{className:"flex gap-2 justify-end",children:[e(es,{variant:"outline",size:"sm",onClick:()=>{h(""),f(""),v("")},disabled:y||s,children:"Limpar"}),e(es,{size:"sm",onClick:async()=>{const e=Number(m);(e||0===e)&&(await c({percentProgress:e,timeProgress:Kx(p)||"00:00",comments:g}),h(""),f(""),v(""))},disabled:b||s,children:s?"Reportando...":"Reportar"})]})]}),r.reports.length>0&&a("div",{className:"space-y-3",children:[e("h4",{className:"text-sm font-medium",children:"Histórico de reportes"}),e("div",{className:"space-y-2",children:r.reports.map(a=>e(eb,{report:a,onEdit:()=>l(a),onDelete:()=>u(a.id),disabled:!n},a.id))})]}),e(Jx,{open:!!o,onOpenChange:e=>!e&&l(null),report:o,onSave:d,isSubmitting:s})]})}function eb({report:t,onEdit:r,onDelete:n,disabled:i}){const s=t.date?new Date(t.date):null,o=Xx(t.percentProgress);return a("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[e("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[a("div",{className:"flex items-center gap-2 text-sm",children:[e("span",{className:"font-medium truncate",children:t.userName}),s&&e("span",{className:"text-xs text-muted-foreground",children:s.toLocaleDateString("pt-BR")})]}),a("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[a("span",{style:{color:o||void 0},className:"font-semibold",children:[t.percentProgress,"%"]}),t.timeProgress&&a("span",{children:["Tempo: ",Qx(t.timeProgress)]})]}),t.comments&&e("p",{className:"text-xs text-muted-foreground mt-1",children:t.comments})]}),!i&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[e(bo,{onClick:r,children:"Editar"}),e(bo,{className:"text-destructive",onClick:n,children:"Excluir"})]})]})]})}function ab({predecessors:t=[],availablePredecessors:r=[],onAdd:i,onRemove:s,disabled:o=!1}){const[l,c]=n.useState(""),d=r.filter(e=>!t.some(a=>a.predecessorId===e.id));return a("div",{className:"space-y-6 p-1",children:[!o&&d.length>0&&a("div",{className:"flex items-end gap-3",children:[a("div",{className:"flex-1 space-y-2",children:[e(ns,{children:"Adicionar predecessor"}),a(Ws,{value:l,onValueChange:c,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione uma ação"})}),e(Xs,{children:d.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]}),a(es,{size:"sm",onClick:()=>{l&&i&&(i(l),c(""))},disabled:!l,children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),t.length>0?e("div",{className:"space-y-2",children:t.map(t=>a("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[a("div",{className:"flex items-center gap-3",children:[t.predecessorCode&&e("span",{className:"text-xs text-muted-foreground font-mono",children:t.predecessorCode}),e("span",{className:"text-sm font-medium",children:t.predecessorName}),null!=t.predecessorStatus&&e(Wx,{status:t.predecessorStatus})]}),!o&&s&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),e(xo,{align:"end",children:e(bo,{className:"text-destructive",onClick:()=>s(t.predecessorId),children:"Remover"})})]})]},t.id))}):e("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function tb({costs:t=[],onAdd:r,onEdit:n,onDelete:s,disabled:o=!1}){const[l,c]=i(""),[d,u]=i(""),m=t.reduce((e,a)=>e+(a.value||0),0);return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[e("span",{className:"text-sm font-medium",children:"Custo total realizado"}),a("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",m.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!o&&r&&a("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e("h4",{className:"text-sm font-medium",children:"Adicionar custo"}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Descrição"}),e(ts,{value:l,onChange:e=>c(e.target.value),placeholder:"Descrição do custo"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Valor (R$)"}),e(ts,{type:"number",min:0,step:.01,value:d,onChange:e=>u(e.target.value),placeholder:"0,00"})]})]}),e("div",{className:"flex justify-end",children:a(es,{size:"sm",onClick:()=>{l&&d&&r&&(r({description:l,value:Number(d),date:(new Date).toISOString()}),c(""),u(""))},disabled:!l||!d,children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),t.length>0?e("div",{className:"space-y-2",children:t.map(t=>a("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:t.description}),t.date&&e("p",{className:"text-xs text-muted-foreground",children:new Date(t.date).toLocaleDateString("pt-BR")})]}),a("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",t.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!o&&(n||s)&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[n&&e(bo,{onClick:()=>n(t),children:"Editar"}),s&&e(bo,{className:"text-destructive",onClick:()=>s(t.id),children:"Excluir"})]})]})]})]},t.id))}):e("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function rb({comments:t=[],currentUserId:r,onAdd:n,onEdit:s,onDelete:o,disabled:l=!1,maxLength:c=4e3}){const[d,u]=i(""),[m,h]=i(!1),[p,f]=i(null),[g,v]=i(""),x=()=>{f(null),v("")};return a("div",{className:"space-y-6 p-1",children:[!l&&n&&a("div",{className:"space-y-3",children:[e(to,{value:d,onChange:e=>u(e.target.value),placeholder:"Adicionar comentário...",maxLength:c,rows:3}),a("div",{className:"flex items-center justify-between",children:[c&&a("span",{className:"text-xs text-muted-foreground",children:[d.length,"/",c]}),a("div",{className:"flex gap-2 ml-auto",children:[e(es,{variant:"outline",size:"sm",onClick:()=>u(""),disabled:!d||m,children:"Limpar"}),e(es,{size:"sm",onClick:async()=>{if(d.trim()&&n){h(!0);try{await n(d),u("")}finally{h(!1)}}},disabled:!d.trim()||m,children:m?"Enviando...":"Comentar"})]})]})]}),a("div",{className:"space-y-1",children:[t.length>0?a("div",{className:"flex items-center gap-2 mb-3",children:[e("span",{className:"text-sm font-medium",children:"Comentários"}),e(no,{variant:"info",className:"text-[10px] px-1.5 py-0",children:t.length})]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(La,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),t.map(t=>a("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[e("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:t.userPhotoUrl?e("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[a("div",{className:"flex items-center gap-2 text-sm",children:[e("span",{className:"font-medium truncate",children:t.userName}),t.userEmail&&e("span",{className:"text-xs text-muted-foreground truncate",children:t.userEmail}),e("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:nb(t.dateEdited||t.dateCreation)}),t.dateEdited&&e("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),p===t.id?a("div",{className:"space-y-2",children:[e(to,{value:g,onChange:e=>v(e.target.value),maxLength:c,rows:3}),a("div",{className:"flex gap-2 justify-end",children:[e(es,{variant:"outline",size:"sm",onClick:x,disabled:m,children:"Cancelar"}),e(es,{size:"sm",onClick:()=>(async e=>{if(g.trim()&&s){h(!0);try{await s({...e,text:g,stringText:g}),f(null),v("")}finally{h(!1)}}})(t),disabled:!g.trim()||m,children:m?"Salvando...":"Salvar"})]})]}):e("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.stringText||t.text})]}),!l&&r===t.userId&&p!==t.id&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[s&&e(bo,{onClick:()=>(e=>{f(e.id),v(e.stringText||e.text)})(t),children:"Editar"}),o&&e(bo,{className:"text-destructive",onClick:()=>(async e=>{if(o){h(!0);try{await o(e)}finally{h(!1)}}})(t.id),children:"Excluir"})]})]})]},t.id))]})]})}function nb(e){if(!e)return"";const a=new Date(e);return`${a.toLocaleDateString("pt-BR")} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ib({history:t=[],isLoading:r=!1}){return r?e("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===t.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(Ae,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum registro no histórico"})]}):e("div",{className:"p-1",children:a("div",{className:"relative",children:[e("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),e("div",{className:"space-y-0",children:t.map((t,r)=>a("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[e("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:t.icon?e("span",{className:"text-xs text-primary",children:t.icon}):e("div",{className:"h-2 w-2 rounded-full bg-primary"})}),a("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[a("div",{children:[e("h4",{className:"text-sm font-medium",children:t.translateEvent||t.eventName}),t.eventDescription&&e("p",{className:"text-xs text-muted-foreground",children:t.eventDescription})]}),a("div",{className:"flex items-center gap-2",children:[e("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:t.userPhotoUrl?e("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"min-w-0",children:[e("span",{className:"text-xs font-medium truncate block",children:t.userName}),t.userEmail&&e("span",{className:"text-[10px] text-muted-foreground truncate block",children:t.userEmail})]})]}),a("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[a("div",{className:"flex items-center gap-1",children:[e(Oe,{className:"h-3 w-3"}),e("span",{children:sb(t.date)})]}),a("div",{className:"flex items-center gap-1",children:[e(Ae,{className:"h-3 w-3"}),e("span",{children:ob(t.date)})]}),t.isMobileRequest&&a("div",{className:"flex items-center gap-1",children:[e(za,{className:"h-3 w-3"}),e("span",{children:"Via app"})]})]})]})]},t.id))})]})})}function sb(e){return new Date(e).toLocaleDateString("pt-BR")}function ob(e){return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function lb({attachments:r=[],onUpload:n,onDelete:s,onRename:o,onDownload:l,onView:c,disabled:u=!1}){const m=d(null),[h,p]=i(null),[f,g]=i(""),v=async e=>{f.trim()&&o&&(await o(e.id,f),p(null),g(""))},x=()=>{p(null),g("")};return a("div",{className:"space-y-4 p-1",children:[!u&&n&&a(t,{children:[e("input",{ref:m,type:"file",multiple:!0,className:"hidden",onChange:e=>{const a=e.target.files;if(a&&n){for(let e=0;e<a.length;e++){const t=a.item(e);t&&n(t)}m.current&&(m.current.value="")}}}),a(es,{size:"sm",onClick:()=>m.current?.click(),children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),r.length>0?e("div",{className:"space-y-2",children:r.map(r=>a("div",{className:Ki("flex items-center gap-3 rounded-lg border bg-card p-3",r.status===Rx.error&&"border-destructive/50 bg-destructive/5",r.status===Rx.canceled&&"opacity-50"),children:[e("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:e("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:r.extension.replace(".","").substring(0,4)})}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[h===r.id?a("div",{className:"flex items-center gap-2",children:[e("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:f,onChange:e=>g(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v(r),"Escape"===e.key&&x()},autoFocus:!0}),e(es,{size:"sm",variant:"outline",onClick:x,children:"Cancelar"}),e(es,{size:"sm",onClick:()=>v(r),children:"Salvar"})]}):e("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>c?.(r.id),children:r.name}),(r.status===Rx.uploading||r.status===Rx.waiting)&&e(Cm,{value:r.progress||0,className:"h-1.5"}),r.status===Rx.error&&e("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),r.status===Rx.duplicateItem&&e("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),r.status===Rx.canceled&&e("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),a("div",{className:"flex items-center gap-2",children:[r.status===Rx.done&&a(t,{children:[e("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:cb(r.size)}),a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[o&&!u&&e(bo,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");p(e.id),g(a)})(r),children:"Renomear"}),c&&e(bo,{onClick:()=>c(r.id),children:"Visualizar"}),l&&e(bo,{onClick:()=>l(r.id),children:"Download"}),s&&!u&&a(t,{children:[e(Co,{}),e(bo,{className:"text-destructive",onClick:()=>s(r.id),children:"Excluir"})]})]})]})]}),r.status===Rx.uploading&&e(es,{variant:"outline",size:"sm",onClick:()=>s?.(r.id),children:"Cancelar"})]})]},r.id))}):a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(Fa,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function cb(e){if(0===e)return"0 B";const a=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,a)).toFixed(1))} ${["B","KB","MB","GB"][a]}`}function db(t){const{formData:r,isLoading:n,isSaving:i,activeTab:s,isFormDisabled:o,updateField:l,setActiveTab:c,save:d,changeStatus:u,remove:m,cancel:h}=qx(t),{isNew:p=!1,config:f,users:g,places:v,actionTypes:x,causes:b,parentActions:y,progress:N,predecessors:w,availablePredecessors:C,costs:k,comments:_,history:S,attachments:A,attachmentsSlot:D,commentsSlot:P,historySlot:E,onAddPredecessor:T,onRemovePredecessor:I,onAddCost:M,onEditCost:R,onDeleteCost:L,onAddComment:z,onEditComment:F,onDeleteComment:U,onUploadAttachment:j,onDeleteAttachment:O,onRenameAttachment:B,onDownloadAttachment:$,onViewAttachment:V}=t;if(n&&!r.id)return e(oo,{isLoading:!0,children:e("div",{})});const q=function(e){if(!e)return[];return{[Sx.waitingStart]:[Sx.running,Sx.suspended,Sx.canceled],[Sx.running]:[Sx.effectivenessCheck,Sx.done,Sx.suspended,Sx.canceled],[Sx.effectivenessCheck]:[Sx.running,Sx.done,Sx.suspended,Sx.canceled],[Sx.done]:[Sx.running],[Sx.suspended]:[Sx.running,Sx.canceled],[Sx.canceled]:[Sx.waitingStart]}[e]||[]}(r.statusId);return a("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[a("div",{className:"flex items-center gap-4",children:[h&&e(es,{variant:"ghost",size:"icon",onClick:h,children:e(Pe,{className:"h-4 w-4"})}),a("div",{className:"space-y-1",children:[a("div",{className:"flex items-center gap-3",children:[e("h1",{className:"text-lg font-semibold",children:p?"Nova Ação":r.name||"Plano de Ação"}),!p&&r.statusId&&e(Wx,{status:r.statusId})]}),r.code&&e("p",{className:"text-xs text-muted-foreground font-mono",children:r.code})]})]}),a("div",{className:"flex items-center gap-2",children:[!p&&q.length>0&&!o&&a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"outline",size:"sm",children:"Alterar Status"})}),e(xo,{align:"end",children:q.map(a=>e(bo,{onClick:()=>u(a),children:jx[a]},a))})]}),!p&&t.onDelete&&a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",children:e(Ea,{className:"h-4 w-4"})})}),e(xo,{align:"end",children:e(bo,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),e("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e("div",{className:"max-w-4xl mx-auto px-6 py-6",children:a(Fd,{value:s,onValueChange:c,children:[a(Ud,{className:"mb-6",children:[e(jd,{value:"general",children:"Geral"}),!p&&e(jd,{value:"progress",children:"Progresso"}),!p&&f?.enablePredecessors&&e(jd,{value:"predecessors",children:"Predecessores"}),!p&&f?.enableCosts&&e(jd,{value:"costs",children:"Custos"}),!p&&f?.enableAttachments&&e(jd,{value:"attachments",children:"Anexos"}),!p&&f?.enableComments&&e(jd,{value:"comments",children:"Comentários"}),!p&&f?.enableHistory&&e(jd,{value:"history",children:"Histórico"})]}),e(Od,{value:"general",children:e(Hx,{formData:r,updateField:l,disabled:o,users:g,places:v,actionTypes:x,causes:b,parentActions:y,config:f})}),!p&&e(Od,{value:"progress",children:e(Zx,{...t})}),!p&&f?.enablePredecessors&&e(Od,{value:"predecessors",children:e(ab,{predecessors:w,availablePredecessors:C,onAdd:T,onRemove:I,disabled:o})}),!p&&f?.enableCosts&&e(Od,{value:"costs",children:e(tb,{costs:k,onAdd:M,onEdit:R,onDelete:L,disabled:o})}),!p&&f?.enableAttachments&&e(Od,{value:"attachments",children:D||e(lb,{attachments:A,onUpload:j,onDelete:O,onRename:B,onDownload:$,onView:V,disabled:o})}),!p&&f?.enableComments&&e(Od,{value:"comments",children:P||e(rb,{comments:_,onAdd:z,onEdit:F,onDelete:U,disabled:o})}),!p&&f?.enableHistory&&e(Od,{value:"history",children:E||e(ib,{history:S})})]})})}),a("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[h&&e(es,{variant:"outline",onClick:h,disabled:i,children:"Cancelar"}),e(es,{onClick:d,disabled:i||o,children:i?"Salvando...":"Salvar"})]})]})}const ub=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function mb(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const a=e/1024;if(a<1024)return`${Math.round(a)} KB`;const t=a/1024;if(t<1024)return`${Math.round(t)} MB`;const r=t/1024;return Math.round(100*r)/100+" GB"}function hb(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function pb({storedFile:t,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:s,minSizeInBytes:l=1,maxSizeInBytes:c=314572800,showDownloadButton:u=!0,showViewButton:m=!0,showReplaceButton:h=!0,showCloseButton:p=!0,required:f=!1,touched:g=!1,disabled:v=!1,error:x,onFileSelect:b,onFileRemove:y,onFileReplace:N,onDownload:w,onView:C,className:k}){const _=d(null),[A,D]=i(null),[P,E]=i(null),[T,I]=i(!1),M=A||t,R=A?.name||t?.name||"",L=A?.size||t?.size;R&&hb(R);const z=r||R,F=u&&!A&&!!t,U=m&&!A&&!!t,j=!!P||!!x||f&&g&&!M,O=!!M,B=o(e=>{if(ub.includes(e.type))return{type:"forbidden-type"};if(e.size<=l)return{type:"min-size"};if(e.size>=c)return{type:"max-size"};if(n?.length){const a=hb(e.name);if(!n.includes(a))return{type:"extension",message:s}}return null},[l,c,n,s]),$=o(e=>{const a=e.target.files?.[0];if(!a)return;const t=B(a);if(t)return E(t),D(null),void(_.current&&(_.current.value=""));E(null),D(a),b?.(a),_.current&&(_.current.value="")},[B,b]),V=o(e=>{if(e.preventDefault(),e.stopPropagation(),v)return;const a=e.dataTransfer.files?.[0];if(!a)return;const t=B(a);if(t)return E(t),void D(null);E(null),D(a),b?.(a)},[v,B,b]),q=o(e=>{e.preventDefault(),e.stopPropagation()},[]),W=o(()=>{N?.(),_.current?.click()},[N]),H=o(()=>{D(null),E(null),y?.(),_.current&&(_.current.value="")},[y]),G=o(async()=>{if(!T&&t&&w){I(!0);try{await w(t)}finally{I(!1)}}},[T,t,w]),Y=o(()=>{t&&C&&C(t)},[t,C]),K=o(()=>{v||_.current?.click()},[v]),Q=(()=>{if(x)return x;if(!P)return f&&g&&!M?"Campo obrigatório":null;switch(P.type){case"extension":return P.message||"Extensão de arquivo não permitida";case"forbidden-type":return"Tipo de arquivo não permitido";case"min-size":return`Tamanho mínimo: ${mb(l)}`;case"max-size":return`Tamanho máximo: ${mb(c)}`;default:return"Erro no arquivo"}})();return a("div",{className:Ki("space-y-1",k),children:[e("div",{className:Ki("rounded-md border border-dashed transition-colors",O&&"border-solid border-border",!O&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",j&&"border-destructive border-solid",v&&"opacity-50 pointer-events-none"),children:a("div",O?{className:"flex items-center justify-between px-3 min-h-[36px]",children:[a("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e(xe,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("p",{className:"text-xs truncate",children:z})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[null!=L&&e("span",{className:"text-xs text-muted-foreground",children:mb(L)}),a("div",{className:"flex items-center gap-0.5",children:[F&&w&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:G,children:e(Ce,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Download"})]}),U&&C&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:e(me,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Visualizar"})]}),h&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:W,children:e(Je,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Substituir"})]}),p&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:H,children:e(S,{className:"h-3 w-3 text-muted-foreground"})})}),e(Do,{children:"Remover"})]})]})]})]}:{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:K,onKeyDown:e=>"Enter"===e.key&&K(),onDrop:V,onDragOver:q,children:[e(Ua,{className:"h-4 w-4 text-muted-foreground"}),a("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",e("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),Q&&e("p",{className:"text-xs text-destructive",children:Q}),e("input",{ref:_,type:"file",className:"hidden",accept:n?.map(e=>`.${e}`).join(","),onChange:$,disabled:v})]})}var fb,gb,vb,xb,bb,yb;function Nb(e){switch(e.type){case fb.text:return e.textValue;case fb.number:return e.numberValue;case fb.date:return e.dateValue;case fb.time:return e.timeValue;case fb.url:case fb.singleSelection:case fb.multiSelection:return e.itemsValue;case fb.questions:return e.questionsValue;case fb.readOnlyText:return e.textValue;default:return null}}function wb(e,a){if(!a)return!0;const t=null!=Nb(e)&&""!==Nb(e)&&!(Array.isArray(Nb(e))&&0===Nb(e).length);return!1!==e.isActive||t}function Cb(e){return e.filter(e=>e.type!==fb.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===fb.text?e.textValue:void 0,numberValue:e.type===fb.number?e.numberValue:void 0,dateValue:e.type===fb.date?e.dateValue:void 0,timeValue:e.type===fb.time?e.timeValue:void 0,itemsValue:[fb.url,fb.singleSelection,fb.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===fb.questions?e.questionsValue:void 0}))}function kb(e,a){return a?.length?e.map(e=>{const t=a.find(a=>a.formFieldAssociationId===e.id);if(!t)return e;const r={...e};switch(e.type){case fb.text:r.textValue=t.textValue;break;case fb.number:r.numberValue=t.numberValue;break;case fb.date:r.dateValue=t.dateValue;break;case fb.time:r.timeValue=t.timeValue;break;case fb.url:case fb.singleSelection:case fb.multiSelection:r.itemsValue=t.itemsValue||[];break;case fb.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function _b(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===fb.readOnlyText)return;const t=Nb(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===fb.number&&null!=t){const r=e.config;null!=r?.min&&t<r.min&&a.push(e.id),null!=r?.max&&t>r.max&&a.push(e.id)}}),{valid:0===a.length,invalidFields:[...new Set(a)]}}function Sb({field:t}){return a("div",{className:"space-y-1",children:[t.name&&e("p",{className:"text-sm font-medium text-foreground",children:t.name}),t.description&&e("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.description}),t.textValue&&e("p",{className:"text-sm text-muted-foreground italic",children:t.textValue})]})}function Ab({field:t,readOnly:r,onChange:n}){const i=t.config,s=i?.multiline??!1,o=r||t.readOnly,l=e=>{n?.({...t,textValue:e})};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),s?e(to,{value:t.textValue||"",onChange:e=>l(e.target.value),placeholder:t.placeholder,disabled:o,rows:4}):e(ts,{value:t.textValue||"",onChange:e=>l(e.target.value),placeholder:t.placeholder,disabled:o})]})}function Db({field:t,readOnly:r,onChange:n}){const i=r||t.readOnly,s=t.dateValue?"string"==typeof t.dateValue?t.dateValue.substring(0,10):new Date(t.dateValue).toISOString().substring(0,10):"";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"date",value:s,onChange:e=>{return a=e.target.value,void n?.({...t,dateValue:a||void 0});var a},placeholder:t.placeholder,disabled:i})]})}function Pb({field:t,readOnly:r,onChange:n}){const i=r||t.readOnly,s=e=>{if(!e)return;const[a,t]=e.split(":").map(Number);return 60*a+t};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"time",value:(e=>{if(null==e)return"";const a=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`})(t.timeValue),onChange:e=>n?.({...t,timeValue:s(e.target.value)}),placeholder:t.placeholder,disabled:i})]})}function Eb({field:t,readOnly:r,onChange:n}){const s=t.config,o=s?.multiple??!1,l=r||t.readOnly,[c,d]=i(""),u=t.itemsValue||[],m=()=>{if(!c.trim())return;const e={value:crypto.randomUUID(),text:c.trim()};n?.({...t,itemsValue:[...u,e]}),d("")};if(!o){const r=u[0]?.text||"";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),a("div",{className:"flex items-center gap-2",children:[e(ts,{type:"url",value:r,onChange:e=>(e=>{const a={value:e,text:e};n?.({...t,itemsValue:e?[a]:[]})})(e.target.value),placeholder:t.placeholder||"https://",disabled:l}),r&&e(es,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:e("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:e(Ze,{className:"h-4 w-4"})})})]})]})}return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),!l&&a("div",{className:"flex items-center gap-2",children:[e(ts,{type:"url",value:c,onChange:e=>d(e.target.value),placeholder:t.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),e(es,{variant:"outline",size:"icon",onClick:m,disabled:!c.trim(),className:"flex-shrink-0",children:e(Y,{className:"h-4 w-4"})})]}),u.length>0&&e("div",{className:"space-y-1",children:u.map((r,i)=>a("div",{className:"flex items-center gap-2 text-sm",children:[e("a",{href:r.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:r.text}),!l&&e(es,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(e=>{const a=u.filter((a,t)=>t!==e);n?.({...t,itemsValue:a})})(i),children:e(q,{className:"h-3 w-3"})})]},r.value))})]})}function Tb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"number",value:t.numberValue??"",onChange:e=>(e=>{if(""===e)return void n?.({...t,numberValue:void 0});const a=parseFloat(e);isNaN(a)||n?.({...t,numberValue:a})})(e.target.value),placeholder:t.placeholder,disabled:s,min:i?.min,max:i?.max,step:o}),null!=i?.min&&null!=i?.max&&a("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function Ib({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.viewMode??vb.dropdown,l=i?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(a=>a.value===e.value))||[],c=t.itemsValue?.[0]?.value||"",d=e=>{const a=l.find(a=>a.value===e);if(!a)return;const r={value:a.value,text:a.text,isActive:a.isActive};n?.({...t,itemsValue:[r]})};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),o===vb.dropdown&&a(Ws,{value:c,onValueChange:d,disabled:s,children:[e(Ys,{children:e(Gs,{placeholder:t.placeholder||"Selecione..."})}),e(Xs,{children:l.map(t=>a(Zs,{value:t.value,children:[t.text,!1===t.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},t.value))})]}),(o===vb.radio||o===vb.buttons)&&e(km,{value:c,onValueChange:d,disabled:s,className:Ki(o===vb.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>a("div",{className:"flex items-center gap-2",children:[e(_m,{value:r.value,id:`${t.id}-${r.value}`}),a(ns,{htmlFor:`${t.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))}),!s&&c&&!t.required&&e("button",{type:"button",onClick:()=>{n?.({...t,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function Mb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.viewMode??vb.dropdown,l=i?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(a=>a.value===e.value))||[],c=new Set(t.itemsValue?.map(e=>e.value)||[]);return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),(t.itemsValue?.length??0)>0&&e("div",{className:"flex flex-wrap gap-1.5",children:t.itemsValue.map(r=>a(no,{variant:"secondary",className:"gap-1 pr-1",children:[e("span",{className:"text-xs",children:r.text}),!s&&e("button",{type:"button",onClick:()=>(e=>{const a=(t.itemsValue||[]).filter(a=>a.value!==e);n?.({...t,itemsValue:a})})(r.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:e(S,{className:"h-3 w-3"})})]},r.value))}),!s&&e("div",{className:Ki(o===vb.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:l.map(r=>a("div",{className:"flex items-center gap-2",children:[e(ao,{id:`${t.id}-${r.value}`,checked:c.has(r.value),onCheckedChange:()=>(e=>{const a=t.itemsValue||[],r=a.some(a=>a.value===e.value)?a.filter(a=>a.value!==e.value):[...a,{value:e.value,text:e.text,isActive:e.isActive}];n?.({...t,itemsValue:r})})(r),disabled:s}),a(ns,{htmlFor:`${t.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))})]})}function Rb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.questions||[],l=i?.options||[],c=t.questionsValue||[];return 0===o.length||0===l.length?a("div",{className:"space-y-1.5",children:[e(ns,{children:t.name}),e("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e("div",{className:"border rounded-md overflow-x-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),l.map(a=>e("th",{className:"text-center p-2 font-medium min-w-[80px]",children:a.text},a.value))]})}),e("tbody",{children:o.map((r,i)=>a("tr",{className:Ki(i<o.length-1&&"border-b"),children:[e("td",{className:"p-2 text-muted-foreground",children:r.text}),l.map(a=>{return e("td",{className:"text-center p-2",children:e(km,{value:(i=r.value,c.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:e=>((e,a,r,i)=>{const s={questionValue:e,questionText:a,optionValue:r,optionText:i},o=c.filter(a=>a.questionValue!==e);o.push(s),n?.({...t,questionsValue:o})})(r.value,r.text,e,a.text),disabled:s,className:"flex justify-center",children:e(_m,{value:a.value,id:`${t.id}-${r.value}-${a.value}`})})},a.value);var i})]},r.value))})]})})]})}function Lb({fields:a,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const s=o(e=>{if(i?.(e),n){const t=a.map(a=>a.id===e.id?e:a);n(t)}},[a,n,i]),l=a.filter(e=>wb(e,r));return 0===l.length?null:e("div",{className:"space-y-4",children:l.map(a=>e(zb,{field:a,readOnly:t,onChange:s},a.id))})}function zb({field:a,readOnly:t,onChange:r}){const n={field:a,readOnly:t,onChange:r};switch(a.type){case fb.readOnlyText:return e(Sb,{...n});case fb.text:return e(Ab,{...n});case fb.date:return e(Db,{...n});case fb.time:return e(Pb,{...n});case fb.url:return e(Eb,{...n});case fb.number:return e(Tb,{...n});case fb.singleSelection:return e(Ib,{...n});case fb.multiSelection:return e(Mb,{...n});case fb.questions:return e(Rb,{...n});default:return null}}function Fb({queryParams:t,events:r,softwares:n,users:s=[],permissions:l={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:c=!1,onFilter:d,onReset:u,onExport:m,onSoftwareChange:h}){const[p,f]=i(t.softwareId),[g,v]=i(t.eventId),[x,b]=i(t.userId||"all"),[y,N]=i(Ub(t.startDate)),[w,C]=i(Ub(t.endDate)),k=o(e=>{const a=parseInt(e);f(a),h?.(a)},[h]),_=o(()=>{d({...t,softwareId:p,eventId:g,userId:"all"===x?void 0:x,startDate:new Date(y),endDate:new Date(w),software:n.find(e=>e.id===p)?.software||t.software,event:r.find(e=>e.id===g)?.name||t.event})},[t,p,g,x,y,w,n,r,d]),S=o(()=>{const e=new Date;e.setHours(0,0,0,0),N(Ub(e)),C(Ub(e)),v(t.eventId),l.viewAllEvents&&b("all"),u?.()},[t.eventId,l.viewAllEvents,u]),A=l.viewOnlyMyEvents&&!l.viewAllEvents,D=p&&g&&y&&w;return a("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[a("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Módulo *"}),a(Ws,{value:String(p),onValueChange:k,disabled:c,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),e(Xs,{children:n.map(a=>e(Zs,{value:String(a.id),className:"text-xs",children:a.translation},a.id))})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Evento *"}),a(Ws,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:c,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),e(Xs,{children:r.map(a=>e(Zs,{value:String(a.id),className:"text-xs",children:a.translation},a.id))})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Usuário *"}),a(Ws,{value:x,onValueChange:b,disabled:c||A,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),a(Xs,{children:[e(Zs,{value:"all",className:"text-xs",children:"Todos"}),s.map(a=>e(Zs,{value:a.id,className:"text-xs",children:a.name},a.id))]})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"De *"}),e(ts,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",max:w,disabled:c})]}),a("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Até *"}),e(ts,{type:"date",value:w,onChange:e=>C(e.target.value),className:"h-8 text-xs",min:y,disabled:c})]}),a("div",{className:"flex items-center gap-2 ml-auto",children:[a(es,{variant:"outline",size:"sm",onClick:S,disabled:c,children:[e(ja,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),l.download&&m&&a(es,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:c,children:[e(Ce,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),a(es,{size:"sm",onClick:_,disabled:c||!D,children:[e(Ie,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Ub(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function jb(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:Bb(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Ob(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Ob(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function Bb(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function $b(e,a){const t=[],r={...Kb,...a?.labels},n=e.eventName;t.push({name:r.event,value:n});const i=e.entities?.[0];if(i&&(t.push({name:r.entityName,value:Vb(i)}),i.description&&t.push({name:r.description,value:i.description}),i.justification&&t.push({name:r.justification,value:i.justification}),i.statusName&&t.push({name:r.status,value:i.statusName}),i.equipmentType&&t.push({name:r.type,value:i.equipmentType}),i.extra?.length)){[...new Set(i.extra.map(e=>e.property))].forEach(e=>{const a=i.extra.filter(a=>a.property===e).map(e=>e.value||"").join(", ");t.push({name:Gb(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=qb(e,n,a?.translateProperty),s=Wb(e,null,n,r,a);s&&t.push({name:i,value:s})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Vb(e);return`(${e.softwareName||e.type}) ${a}`});a.length&&t.push({name:r.references,value:a.join(", ")})}}),i?.isElectronicSigned&&t.push({name:r.security,value:"🛡️ "+r.electronicSigned}),t.push({name:r.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const s=a?.formatDate?a.formatDate(e.dateTime):Yb(e.dateTime);return t.push({name:r.accomplishedIn,value:s}),t}function Vb(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function qb(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=Gb(e.property);return t?t(a,r):r}function Wb(e,a,t,r,n){if(e.propertyResource||(e.propertyResource=a?`${a.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const a=qb(e,t,n?.translateProperty),i=function(e,a){switch(e.state){case"Added":return a.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?a.stateRemoved:a.stateModified;default:return""}}(e,r);let s=`${a}: "${Hb(e,"newValue",r,n)}" ${i}`;const o=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Wb(a,e,t,r,n)));return o.some(Boolean)&&(s+="\n"+o.filter(Boolean).join("\n")),s}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Wb(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=Hb(e,"oldValue",r,n),s=Hb(e,"newValue",r,n);return`${a?qb(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${s}"`}const i=Hb(e,"newValue",r,n);return a?`${qb(e,t,n?.translateProperty)}: ${i}`:i}function Hb(e,a,t,r){const n=e[a];return null==n||""===n?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?t.uninformed:"":"string"==typeof n&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const a=new Date(e);return!isNaN(a.getTime())}(n)?r?.formatDate?r.formatDate(n):Yb(n):String(n)}function Gb(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function Yb(e){try{return new Date(e).toLocaleString()}catch{return e}}(gb=fb||(fb={}))[gb.readOnlyText=1]="readOnlyText",gb[gb.text=2]="text",gb[gb.date=3]="date",gb[gb.time=4]="time",gb[gb.url=5]="url",gb[gb.number=6]="number",gb[gb.singleSelection=7]="singleSelection",gb[gb.multiSelection=8]="multiSelection",gb[gb.questions=9]="questions",(xb=vb||(vb={}))[xb.dropdown=1]="dropdown",xb[xb.buttons=2]="buttons",xb[xb.radio=3]="radio",xb[xb.checkbox=4]="checkbox",(yb=bb||(bb={}))[yb.custom=1]="custom",yb[yb.users=2]="users",yb[yb.usersLists=3]="usersLists";const Kb={event:"Evento",entityName:"Item",description:"Descrição",justification:"Justificativa",status:"Status",type:"Tipo",references:"Referências",security:"Segurança",electronicSigned:"Assinatura Eletrônica",accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:"Não informado",stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Qb({documentId:t,onFetchDetails:r,onClose:n,labels:s,translateProperty:l,translatePropertyValue:c,formatDate:d}){const[m,h]=i(!1),[p,f]=i([]),[g,v]=i(null),x=o(async e=>{h(!0),v(null);try{const a=$b(await r(e),{translateProperty:l,translatePropertyValue:c,formatDate:d,labels:s});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{h(!1)}},[r,l,c,d,s]);return u(()=>{t&&x(t)},[t,x]),t?a("div",{className:"flex flex-col h-full bg-background",children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[e("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:e(S,{className:"h-4 w-4"})})]}),e("div",{className:"flex-1 overflow-y-auto",children:m?a("div",{className:"flex items-center justify-center p-6",children:[e(so,{size:"md"}),e("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):g?e("div",{className:"p-6 text-sm text-destructive",children:g}):e("table",{className:"w-full text-xs",children:e("tbody",{children:p.map((t,r)=>a("tr",{className:r%2==0?"bg-background":"bg-muted/20",children:[e("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:t.name}),e("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:e("span",{dangerouslySetInnerHTML:{__html:t.value.replace(/\n/g,"<br />")}})})]},r))})})})]}):null}function Xb({title:t="Trilha de Auditoria",softwares:r,softwareId:n,permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:l,limit:c=2e3,currentUserId:m,labels:h,formatDate:p,anonymousLabel:f="Anônimo"}){const[g,v]=i(!0),[x,b]=i([]),[y,N]=i([]),[w,C]=i([]),[k,_]=i(null),[S,A]=i(!1),D=d(null),P=new Date;P.setHours(0,0,0,0);const[E,T]=i({software:r.find(e=>e.id===n)?.software||"",softwareId:n,event:"All",eventId:1,startDate:P,endDate:P,limit:c,softwares:r,userId:s.viewOnlyMyEvents&&!s.viewAllEvents?m:void 0});u(()=>{(async()=>{v(!0);try{const[e,a]=await Promise.all([l.onFetchEvents(E.softwareId),l.onFetchUsers?.()??Promise.resolve([])]);N(e),C(a),await I(E,e)}catch(e){}finally{v(!1)}})()},[]);const I=o(async(e,a)=>{try{const t=jb((await l.onFetchTrails(e)).data,a||y,r,f);b(t)}catch(t){}},[l,y,r,f]),M=o(async e=>{v(!0),T(e);try{await I(e)}finally{v(!1)}},[I]),R=o(async e=>{try{const a=await l.onFetchEvents(e);N(a)}catch(a){}},[l]),L=o(e=>{_(e.documentId),A(!0)},[]),z=o(()=>{A(!1),_(null)},[]),F=o(async()=>{const e={...E,startDate:P,endDate:P,eventId:1,userId:s.viewAllEvents?void 0:m};T(e),v(!0);try{await I(e)}finally{v(!1)}},[E,I]),U=o(e=>{l.onExport?.(e,x)},[l,x]),j=o(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return a("div",{className:"flex flex-col h-full",children:[e("div",{className:"p-3",children:e(Fb,{queryParams:E,events:y,softwares:r,users:w,permissions:s,isLoading:g,onFilter:M,onReset:F,onExport:s.download?U:void 0,onSoftwareChange:R})}),a("div",{className:"flex flex-1 min-h-0 relative",children:[a("div",{className:Ki("flex-1 overflow-auto transition-all duration-300",S?"mr-[400px]":""),children:[g?a("div",{className:"flex items-center justify-center h-64",children:[e(so,{size:"md"}),e("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===x.length?a("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e(xe,{className:"h-12 w-12 mb-3 opacity-30"}),e("p",{className:"text-sm",children:"Nenhum registro encontrado"}),e("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):a("table",{className:"w-full text-xs border-collapse",children:[e("thead",{className:"sticky top-0 z-10",children:a("tr",{className:"bg-muted/60 border-b border-border",children:[e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(Oa,{className:"h-3 w-3"}),"Módulo"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(Ae,{className:"h-3 w-3"}),"Data"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(qe,{className:"h-3 w-3"}),"Usuário"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(xe,{className:"h-3 w-3"}),"Evento"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),e("th",{className:"px-3 py-2 w-10"})]})}),e("tbody",{children:x.map((t,r)=>a("tr",{onClick:()=>L(t),className:Ki("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",k===t.documentId&&"bg-accent",r%2==0?"bg-background":"bg-muted/10"),children:[e("td",{className:"px-3 py-2 text-foreground",children:t.translatedSoftware}),e("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:t.date?j(t.date.toISOString()):"—"}),e("td",{className:"px-3 py-2 text-foreground",children:t.user}),e("td",{className:"px-3 py-2 text-foreground",children:t.translatedEvent}),e("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:t.entityName,children:t.entityName}),e("td",{className:"px-3 py-2",children:e(me,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},t.documentId||r))})]}),!g&&x.length>0&&a("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[x.length," registro",1!==x.length?"s":""]})]}),e("div",{ref:D,className:Ki("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",S?"translate-x-0":"translate-x-full"),children:S&&e(Qb,{documentId:k,onFetchDetails:l.onFetchDetails,onClose:z,labels:h,translateProperty:l.translateProperty,translatePropertyValue:l.translatePropertyValue,formatDate:p||j})})]})]})}function Jb({open:t,onOpenChange:r,returnSteps:n,initialObservation:s="",title:o="Executar ação",descriptions:l=[],setDefaultApproverOnInit:c=!0,onSubmit:d}){const[u,m]=i(!0),[h,p]=i(c&&n.length>0?n[0].id:null),[f,g]=i(s),v=e=>{m(e),e&&!c?p(null):!e&&!c&&n.length>0&&p(n[0].id)},x=f!==s||!u;return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-[480px]",children:[e(Es,{children:e(Ms,{children:o})}),a("div",{className:"space-y-4",children:[l.length>0&&e("div",{className:"space-y-1 text-sm text-muted-foreground",children:l.map((a,t)=>e("p",{dangerouslySetInnerHTML:{__html:a}},t))}),a("div",{className:"flex gap-4",children:[a("label",{className:"flex items-center gap-2 cursor-pointer",children:[e("input",{type:"radio",name:"approved",checked:u,onChange:()=>v(!0),className:"accent-primary"}),e("span",{className:"text-sm",children:"Aprovar"})]}),a("label",{className:"flex items-center gap-2 cursor-pointer",children:[e("input",{type:"radio",name:"approved",checked:!u,onChange:()=>v(!1),className:"accent-primary"}),e("span",{className:"text-sm",children:"Reprovar e retornar para etapa"})]})]}),a("div",{className:"space-y-1.5",children:[e(ns,{children:"Etapa"}),a(Ws,{value:h??void 0,onValueChange:p,disabled:u,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a etapa"})}),e(Xs,{children:n.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),a("div",{className:"space-y-1.5",children:[e(ns,{children:"Parecer *"}),e(to,{value:f,onChange:e=>g(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),a("p",{className:"text-xs text-muted-foreground text-right",children:[f.length,"/",4e3]})]})]}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),e(es,{onClick:()=>{if(!f.trim())return void C.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=u?null:n.find(e=>e.id===h);d({approved:u,returnStepId:u?null:h,returnType:e?.type??null,observation:f})},disabled:!x,children:"Concluir"})]})]})})}function Zb({open:t,onOpenChange:r,approvers:n,isLoading:o=!1,ignoreUserIds:l=[],onSubmit:c}){const[d,u]=i(null),m=s(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=s(()=>m.map(e=>({value:e.id,label:e.name})),[m]);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-[450px]",children:[e(Es,{children:e(Ms,{children:"Selecionar aprovador"})}),e(oo,{isLoading:o,type:"spinner",children:e("div",{className:"space-y-4",children:e(Wo,{options:h,value:d??void 0,onValueChange:e=>u("string"==typeof e?e:e?.[0]??null),placeholder:"Selecione um aprovador...",searchPlaceholder:"Buscar aprovador..."})})}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),e(es,{onClick:()=>{if(!d)return;const e=m.find(e=>e.id===d);e&&c(e)},disabled:!d||o,children:"Concluir"})]})]})})}function ey(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function ay({text:t,maxLength:r=130}){const[n,s]=i(!1);return t.length<=r?e("span",{children:t}):a("span",{children:[n?t:`${t.substring(0,r)}... `,e("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>s(!n),children:n?"Ler menos":"Ler mais"})]})}function ty({approver:t}){if(1===t.type&&t.approverId)return a(cu,{className:"h-9 w-9 shrink-0",children:[e(du,{src:t.photoUrl,alt:t.name}),e(uu,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]});const r=2===t.type?Sa:3===t.type?je:qe;return e("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:e(r,{className:"h-4 w-4 text-background"})})}function ry({approver:t}){return t.date?a("div",{className:"flex items-center gap-2 flex-wrap",children:[a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[e(Qe,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),e("span",{className:"text-xs text-muted-foreground",children:ey(t.date)}),1!==t.type&&t.approvedUsername&&a("span",{className:"text-xs text-muted-foreground",children:["por ",t.approvedUsername]})]}):t.returnDate?a("div",{className:"flex items-center gap-2 flex-wrap",children:[a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[e(Ba,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),e("span",{className:"text-xs text-muted-foreground",children:ey(t.returnDate)})]}):a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[e(U,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function ny({approver:t}){const r=1!==t.type||t.approverId?t.name:"A definir";return a("div",{children:[2===t.type&&e("p",{className:"text-xs text-muted-foreground",children:"Grupo de usuários"}),3===t.type&&e("p",{className:"text-xs text-muted-foreground",children:"Local"}),e("p",{className:"text-sm font-medium break-words",children:r}),e(ry,{approver:t})]})}function iy({config:t,isLoading:r=!1,onClose:n,onApprove:s,onDefineApprover:l,onRefreshSteps:c,availableApprovers:d=[],isLoadingApprovers:u=!1}){const[m,h]=i(!1),[p,f]=i(!1),[g,v]=i(""),[x,b]=i(""),[y,N]=i(!1),[w,C]=i(""),k=r||m,_=o((e,a)=>{v(e),b(a??""),f(!0)},[]),A=o(async e=>{f(!1),h(!0);if(!await s(t.associationId,{stepApproverId:g,...e}))return _(g,e.observation),void h(!1);n(),h(!1)},[t.associationId,g,s,n,_]),D=o(e=>{C(e),N(!0)},[]),P=o(async e=>{N(!1),h(!0),await l(t.associationId,w,e),await(c?.(t.associationId)),h(!1)},[t.associationId,w,l,c]),E=t.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],T=(e,a)=>t.canApprove&&e.isCurrentStep&&a.approverId&&!a.date&&a.canApprove,I=(e,a)=>!t.flowReproved&&e.isCurrentStep&&1===a.type&&a.canApprove&&(!a.approverId||a.isToBeDefined);return a("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[a("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:t.color},children:[e(es,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:e(S,{className:"h-5 w-5"})}),e("span",{className:"text-lg font-medium",children:t.title})]}),k?e(oo,{isLoading:!0,type:"spinner",className:"flex-1",children:e("div",{})}):a("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[t.approvalFlowInfo.length>0&&e("div",{className:"space-y-1",children:t.approvalFlowInfo.map((a,t)=>e("div",{className:Ki("flex items-center gap-1.5 text-sm",a.color&&"rounded-lg px-2 py-1"),style:a.color?{color:a.color,backgroundColor:a.backgroundColor}:void 0,children:a.title?`${a.title}: ${a.value}`:a.value},t))}),e("hr",{className:"border-border"}),t.approvalFlowSteps.map(r=>a("div",{className:Ki("space-y-2",(!r.isCurrentStep||t.flowReproved)&&"opacity-50"),children:[a("p",{className:"font-semibold text-sm",children:[r.index,". Etapa: ",r.name]}),r.description&&e("p",{className:"text-sm text-muted-foreground break-words",children:e(ay,{text:r.description})}),r.returnDate&&a("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[a("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),a("span",{className:"text-xs text-muted-foreground",children:[r.returnUserName," em ",ey(r.returnDate)]})]}),r.returnObservation&&e("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:e(ay,{text:r.returnObservation})})]}),r.approvers.map(t=>a("div",{className:"p-2 space-y-1",children:[a("div",{className:"flex items-center justify-between gap-2",children:[a("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e(ty,{approver:t}),e(ny,{approver:t})]}),T(r,t)&&e(es,{size:"sm",onClick:()=>_(t.id),children:"Aprovar"}),I(r,t)&&e(es,{size:"sm",variant:"outline",onClick:()=>D(t.id),children:"Selecionar"})]}),t.observation&&e("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e(ay,{text:t.observation})}),t.returnObservation&&e("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e(ay,{text:t.returnObservation})})]},t.id))]},r.id))]}),e(Jb,{open:p,onOpenChange:f,returnSteps:t.returnSteps,initialObservation:x,title:t.approveDialogTitle,descriptions:t.approveDialogDescriptions,setDefaultApproverOnInit:t.approveDialogSetDefaultApproverOnInit,onSubmit:A}),e(Zb,{open:y,onOpenChange:N,approvers:d,isLoading:u,ignoreUserIds:E,onSubmit:P})]})}var sy,oy;function ly({users:t,value:r,onChange:n,disabled:l=!1,placeholder:c="Buscar membro da equipe...",confirmRemoval:d=!0,confirmTitle:u="Remover da equipe",confirmMessage:m="Tem certeza que deseja remover este membro da equipe?",emptyMessage:h="Nenhum membro na equipe",className:p}){const[f,g]=i(""),[v,x]=i(!1),[b,y]=i(null),N=s(()=>new Set(r),[r]),w=s(()=>t.filter(e=>N.has(e.id)),[t,N]),C=s(()=>t.filter(e=>!N.has(e.id)).map(e=>({value:e.id,label:e.name})),[t,N]),k=o(e=>{e&&!N.has(e)&&(n([...r,e]),g(""))},[r,n,N]),_=o(e=>{d?(y(e),x(!0)):n(r.filter(a=>a!==e))},[r,n,d]),A=o(()=>{b&&n(r.filter(e=>e!==b)),x(!1),y(null)},[b,r,n]);return a("div",{className:Ki("space-y-3",p),children:[e("div",{className:"flex items-start gap-3",children:e("div",{className:"flex-1",children:e(Wo,{options:C,value:f,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";g(a),a&&k(a)},placeholder:c,searchPlaceholder:"Buscar...",disabled:l})})}),a("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),e("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:w.length})]}),w.length>0?e("div",{className:"space-y-2",children:w.map(t=>a("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[a(cu,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e(du,{src:t.avatar,alt:t.name}),e(uu,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]}),e("div",{className:"flex-1 min-w-0",children:e("p",{className:"text-sm font-medium truncate",title:t.name,dangerouslySetInnerHTML:{__html:t.title||t.name}})}),a("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[t.roleName&&a("span",{className:"flex items-center gap-1",children:[e(de,{className:"h-3.5 w-3.5"}),e("span",{className:"truncate max-w-[120px]",children:t.roleName})]}),t.placeName&&a("span",{className:"flex items-center gap-1",children:[e(je,{className:"h-3.5 w-3.5"}),e("span",{className:"truncate max-w-[120px]",children:t.placeName})]}),e("button",{type:"button",className:Ki("text-muted-foreground hover:text-destructive transition-colors",l&&"opacity-50 pointer-events-none"),onClick:()=>!l&&_(t.id),title:"Remover",children:e(S,{className:"h-4 w-4"})})]})]},t.id))}):a("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e(qe,{className:"h-12 w-12 mb-2 opacity-30"}),e("p",{className:"text-sm",children:h})]}),e(Cs,{open:v,onOpenChange:x,children:a(Ps,{className:"sm:max-w-[400px]",children:[e(Es,{children:e(Ms,{children:u})}),e("p",{className:"text-sm text-muted-foreground",children:m}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>x(!1),children:"Cancelar"}),e(es,{variant:"destructive",onClick:A,children:"Remover"})]})]})})]})}(oy=sy||(sy={}))[oy.ApprovalFlow=1]="ApprovalFlow",oy[oy.Association=2]="Association";export{Cr as AUTH_CONFIG,eu as AccessDeniedDialog,iu as Accordion,lu as AccordionContent,su as AccordionItem,ou as AccordionTrigger,as as ActionButton,as as ActionMenu,bc as ActionMenuItems,lb as ActionPlanAttachmentsTab,rb as ActionPlanCommentsTab,tb as ActionPlanCostTab,Hx as ActionPlanGeneralTab,ib as ActionPlanHistoryTab,db as ActionPlanPage,ab as ActionPlanPredecessorsTab,Jx as ActionPlanProgressDialog,Zx as ActionPlanProgressTab,Wx as ActionPlanStatusBadge,jp as AggregationType,ud as Alert,hd as AlertDescription,ms as AlertDialog,Ns as AlertDialogAction,ws as AlertDialogCancel,gs as AlertDialogContent,ys as AlertDialogDescription,xs as AlertDialogFooter,vs as AlertDialogHeader,fs as AlertDialogOverlay,ps as AlertDialogPortal,bs as AlertDialogTitle,hs as AlertDialogTrigger,md as AlertTitle,ld as AliasRedirect,od as AliasRouteGuard,Bp as AnalysisFunctionality,iv as AppHeader,gv as AppLayout,fv as AppSidebar,sy as ApprovalFlowReturnStep,iy as ApprovalSidenav,Jb as ApproveDialog,Qb as AuditTrailDetails,Fb as AuditTrailFilter,Xb as AuditTrailPage,vl as AuthErrorInterceptor,Ll as AuthProvider,Tl as AuthService,Wo as AutoComplete,cu as Avatar,uu as AvatarFallback,du as AvatarImage,no as Badge,Wc as BaseForm,rm as Blockquote,bv as BodyContent,mu as Breadcrumb,xu as BreadcrumbEllipsis,pu as BreadcrumbItem,fu as BreadcrumbLink,hu as BreadcrumbList,gu as BreadcrumbPage,vu as BreadcrumbSeparator,xg as BurndownPanel,es as Button,yu as ButtonGroup,$x as CLOSED_STATUSES,kr as CRUD_CONFIG,jf as CURRENCY_FIELDS,Nu as Calendar,pd as CallbackPage,is as Card,cs as CardContent,ls as CardDescription,ds as CardFooter,ss as CardHeader,Ql as CardSkeleton,os as CardTitle,hg as CartesianPanel,Fh as ChartContainer,Bh as ChartLegend,$h as ChartLegendContent,Uh as ChartStyle,jh as ChartTooltip,Oh as ChartTooltipContent,ao as Checkbox,Md as Collapsible,Ld as CollapsibleContent,Rd as CollapsibleTrigger,jc as ColorPicker,Zo as ComboTree,Wo as Combobox,Mo as Command,Ro as CommandDialog,Fo as CommandEmpty,Uo as CommandGroup,Lo as CommandInput,Oo as CommandItem,zo as CommandList,jo as CommandSeparator,Bo as CommandShortcut,xv as ContentContainer,nc as ContextMenu,pc as ContextMenuCheckboxItem,mc as ContextMenuContent,sc as ContextMenuGroup,hc as ContextMenuItem,gc as ContextMenuLabel,oc as ContextMenuPortal,cc as ContextMenuRadioGroup,fc as ContextMenuRadioItem,vc as ContextMenuSeparator,xc as ContextMenuShortcut,lc as ContextMenuSub,uc as ContextMenuSubContent,dc as ContextMenuSubTrigger,ic as ContextMenuTrigger,nu as CoreProviders,Pc as CrudActionBar,$g as CrudActionMenu,Og as CrudGrid,Zc as CrudPageInternal,Gc as CrudPagination,Vg as CrudPrimitiveFilterBar,Hc as CrudPrimitivePagination,Bg as CrudPrimitiveTable,zc as CrudTable,Lb as CustomFormFields,Cx as D4SignWidget,Uf as DASHBOARD_STORAGE_KEYS,Di as DATETIME_FORMATS,Ox as DEFAULT_ACTION_TYPES,Ti as DEFAULT_DATETIME_FORMAT,Ei as DEFAULT_LOCALE,Ii as DEFAULT_TIMEZONE,Ug as DashboardForm,cf as DashboardFormTab,$p as DashboardFunctionality,jg as DashboardGeneralView,_g as DashboardGrid,hf as DashboardLanguage,Ig as DashboardList,qp as DashboardListType,Hp as DashboardPageTime,Yp as DashboardPanelDimension,Jp as DashboardPanelOrderBy,Qp as DashboardPanelOrderByType,ef as DashboardPanelPeriod,Ag as DashboardPanelRenderer,tf as DashboardPanelType,uf as DashboardShareType,nf as DashboardUpdateTime,Dg as DashboardView,of as DashboardViewType,Vg as DataFilterBar,wu as DataList,Hc as DataPagination,Bg as DataTable,Cu as DatePicker,Cs as Dialog,Ts as DialogBody,Ss as DialogClose,Ps as DialogContent,Rs as DialogDescription,Is as DialogFooter,Es as DialogHeader,As as DialogOverlay,_s as DialogPortal,Ms as DialogTitle,ks as DialogTrigger,Po as DisabledMenuItem,kx as DocumentSigner,ku as Drawer,Au as DrawerClose,Pu as DrawerContent,Mu as DrawerDescription,Tu as DrawerFooter,Eu as DrawerHeader,Du as DrawerOverlay,Su as DrawerPortal,Iu as DrawerTitle,_u as DrawerTrigger,co as DropdownMenu,yo as DropdownMenuCheckboxItem,xo as DropdownMenuContent,mo as DropdownMenuGroup,bo as DropdownMenuItem,wo as DropdownMenuLabel,ho as DropdownMenuPortal,fo as DropdownMenuRadioGroup,No as DropdownMenuRadioItem,Co as DropdownMenuSeparator,ko as DropdownMenuShortcut,po as DropdownMenuSub,vo as DropdownMenuSubContent,go as DropdownMenuSubTrigger,uo as DropdownMenuTrigger,Rx as EAttachmentItemStatus,fb as ECustomFormFieldType,vb as EFieldViewMode,bb as ESelectionFieldDataSource,Ex as ETaskPlanAssociationType,Dx as ETaskPlanPriority,Sx as ETaskPlanStatus,Ix as ETaskPlanTypeProgress,np as ElectronicSignatureDialog,tc as EllipsisText,kv as EmailService,ac as EmptyState,Wo as EntitySelect,zd as ErrorBoundary,tp as ExportDialog,Jh as ExportFormat,ub as FORBIDDEN_FILE_TYPES,mp as FilePrintType,dp as FileViewerType,Jc as FilterBar,Ls as Form,$s as FormControl,Db as FormDateField,Vs as FormDescription,Fs as FormField,Os as FormItem,Bs as FormLabel,qs as FormMessage,Mb as FormMultiSelectionField,Tb as FormNumericField,Rb as FormQuestionsField,Ib as FormSingleSelectionField,Xl as FormSkeleton,Ab as FormTextField,Pb as FormTimeField,Eb as FormUrlField,zu as Grid,Gu as H1,Yu as H2,Ku as H3,Qu as H4,Jl as HeaderSkeleton,Fu as HoverCard,ju as HoverCardContent,Uu as HoverCardTrigger,Bc as IconPicker,Cp as IframeDialog,ox as ImageEditor,lx as ImageRenderer,tm as InlineCode,ts as Input,Ou as InputGroup,$u as InputGroupAddon,qu as InputGroupButton,Wu as InputGroupInput,Hu as InputGroupTextarea,Of as LINK_PROPERTIES,Ir as LOGO_CONFIG,ns as Label,Zu as Large,Ju as Lead,Gv as LeadershipDialog,Hv as LeadershipForm,Qv as LeadershipPage,nm as List,dg as ListPanel,oo as LoadingState,Dd as LocaleProvider,fd as LoginPage,Mr as MESSAGES,qd as MODULES_DATA,Ff as MONTHS_MAP,Sv as ManageAccessModal,yg as MatrixRiskPanel,ff as MatrixViewType,Ch as Menubar,Ph as MenubarCheckboxItem,Ah as MenubarContent,bh as MenubarGroup,Dh as MenubarItem,Th as MenubarLabel,xh as MenubarMenu,yh as MenubarPortal,wh as MenubarRadioGroup,Eh as MenubarRadioItem,Ih as MenubarSeparator,Mh as MenubarShortcut,Nh as MenubarSub,Sh as MenubarSubContent,_h as MenubarSubTrigger,kh as MenubarTrigger,mv as ModalStateProvider,tu as ModuleAccessGuard,Gd as ModuleGrid,ru as ModuleOfferContent,Td as ModuleProvider,Yd as ModulesContent,Zd as ModulesDialog,Vd as ModulesFooterCards,Wo as MultiSelect,Tp as MultiselectPermissions,am as Muted,im as NavigationMenu,dm as NavigationMenuContent,hm as NavigationMenuIndicator,om as NavigationMenuItem,um as NavigationMenuLink,sm as NavigationMenuList,cm as NavigationMenuTrigger,mm as NavigationMenuViewport,Zg as NavigationProvider,lg as NumericPanel,Qh as OnboardingDialog,wp as OnlineEditorDialog,Xu as P,Bx as PRIORITIES,xr as PROD_PROJECT_ID,Vx as PROGRESS_ALLOWED_STATUSES,pm as PageBreadcrumb,vd as PageMetadataProvider,gm as Pagination,vm as PaginationContent,wm as PaginationEllipsis,xm as PaginationItem,bm as PaginationLink,Nm as PaginationNext,ym as PaginationPrevious,Lf as PaletteType,rg as PanelError,tg as PanelHeader,vf as PanelItemsPerPanel,ng as PanelLoader,ig as PanelNoData,bf as PanelSortType,Nf as PanelState,sg as PanelUnavailable,vg as ParetoPanel,bg as PerformancePanel,gg as PiePanel,Av as PlaceCard,Dv as PlacesList,_f as PlanType,Eo as Popover,Io as PopoverContent,To as PopoverTrigger,Cm as Progress,id as ProtectedRoute,Tr as QUALIEX_CONFIG,Er as QUERY_KEYS,_l as QualiexEnrichmentService,xl as QualiexErrorInterceptor,qc as QualiexUserField,Af as QueriesContextType,Pf as QueriesShareType,Tf as QuickFilterDashboard,km as RadioGroup,_m as RadioGroupItem,Sb as ReadOnlyTextField,Fp as ReportRequestList,Ip as ReportRequestStatus,Dm as ResizableHandle,Am as ResizablePanel,Sm as ResizablePanelGroup,Hh as RichTextEditor,Mf as RiskCriticality,_r as SEARCH_CONFIG,zx as STATUS_COLORS,jx as STATUS_LABELS,Ux as STATUS_MAP,Fx as STATUS_TEXT_COLORS,Ai as SUPPORTED_LOCALES,Ho as ScrollArea,Go as ScrollBar,Ws as Select,Zb as SelectApproverDialog,Xs as SelectContent,Hs as SelectGroup,Zs as SelectItem,Js as SelectLabel,Qs as SelectScrollDownButton,Ks as SelectScrollUpButton,Wo as SelectSearch,eo as SelectSeparator,Ys as SelectTrigger,Gs as SelectValue,us as Separator,Pm as Sheet,Fm as SheetBody,Tm as SheetClose,Lm as SheetContent,Om as SheetDescription,Um as SheetFooter,zm as SheetHeader,Mm as SheetOverlay,Im as SheetPortal,jm as SheetTitle,Em as SheetTrigger,Wm as Sidebar,ov as SidebarActionTrigger,Zm as SidebarContent,Xm as SidebarFooter,eh as SidebarGroup,th as SidebarGroupAction,rh as SidebarGroupContent,ah as SidebarGroupLabel,vv as SidebarHeader,Km as SidebarInput,Ym as SidebarInset,nv as SidebarLogo,nh as SidebarMenu,lh as SidebarMenuAction,ch as SidebarMenuBadge,oh as SidebarMenuButton,ih as SidebarMenuItem,dh as SidebarMenuSkeleton,uh as SidebarMenuSub,hh as SidebarMenuSubButton,mh as SidebarMenuSubItem,qm as SidebarProvider,Gm as SidebarRail,Jm as SidebarSeparator,Zl as SidebarSkeleton,Hm as SidebarTrigger,_x as SignConfigForm,wx as SignWidget,pb as SingleFileUpload,$o as Skeleton,ph as Slider,em as Small,lo as SonnerToaster,so as Spinner,Xh as SplitButton,Xc as Stack,ip as StepSelector,ip as Stepper,Up as StimulsoftViewer,$c as Switch,Pi as TIMEZONES,vh as TabPageContent,gh as TabPageHeader,fh as TabPageLayout,Bl as Table,Vl as TableBody,Yl as TableCaption,Gl as TableCell,ql as TableFooter,Hl as TableHead,$l as TableHeader,rc as TableResizeHandle,Wl as TableRow,yc as TableRowActions,Kl as TableSkeleton,Fd as Tabs,Od as TabsContent,Ud as TabsList,jd as TabsTrigger,ly as TeamSelector,kp as TermsOfUseDialog,_p as TermsOfUseViewer,cg as TextPanel,to as Textarea,rp as Timepicker,lo as Toaster,_c as Toggle,Ac as ToggleGroup,Dc as ToggleGroupItem,cl as TokenManager,el as TokenService,So as Tooltip,Do as TooltipContent,_o as TooltipProvider,Ao as TooltipTrigger,Zo as TreeSelect,Yg as TreeTable,tc as TruncatedCell,cp as UpdatesNotification,Dp as UsersGroupsSelector,ix as VideoEditor,sx as VideoRenderer,yp as ViewerDialog,Cf as VisualizationType,kd as addAppTranslations,zr as assets,ro as badgeVariants,$b as buildDetailRows,Tv as buildHierarchy,Yi as buildModuleUrl,Jf as buildPlacesTree,bp as buildWopiUrl,bu as buttonGroupVariants,Zi as buttonVariants,cx as calculateAspectRatio,Gb as camelToDash,Ki as cn,ed as createCrudPage,Qg as createCrudRoutingConfig,Kg as createRoutingHandlers,Dl as createService,ad as createSimpleSaveHandler,Ul as createSimpleService,Rr as createTranslatedMessages,Xf as currencyFormatter,Xi as debounce,Nl as deriveEmailField,yl as deriveNameField,wl as deriveUsernameField,ji as detectBrowserLocale,$i as detectBrowserPreferences,Oi as detectBrowserTimezone,rx as detectVideoProvider,_v as emailService,dl as errorService,mx as extractImageFileName,Qf as extractNumberFromCurrency,ex as extractVimeoId,Jv as extractYouTubeId,Ev as filterAndPromoteOrphans,Ri as findDatetimeFormat,Mi as findLocale,Li as findTimezone,Iv as flattenTree,mb as formatBytes,Hi as formatCurrency,Wi as formatDate,qi as formatDatetime,hx as formatFileSize,Qx as formatTime,Kx as formatTimeProgress,td as generateCrudConfig,wg as getDefaultPanelSize,Nr as getEnvironmentConfig,Nb as getFieldValue,hb as getFileExtension,Cb as getFormFieldValues,Wf as getLinkFromRow,Cg as getMinPanelSize,gp as getOnlineViewerType,Xx as getProgressColor,Pr as getQualiexApiUrl,pl as getSupabaseClient,fp as getViewerType,xp as getWopiViewer,Gi as handleExternalLink,Bi as inferDatetimeFormat,Bu as inputGroupAddonVariants,Vu as inputGroupButtonVariants,Kf as isCurrency,Dr as isDevEnvironment,wr as isDevSupabaseProject,ux as isImageUrl,Sr as isLovablePreview,Vf as isNullOrEmptyField,Fi as isValidDatetimeFormat,zi as isValidLocale,Ui as isValidTimezone,yx as loadClicksignScript,Fr as logoSrc,lm as navigationMenuTriggerStyle,nx as normalizeVideoUrl,ax as normalizeVimeoUrl,Zv as normalizeYouTubeUrl,tx as parseIframeSrc,Pv as placeService,jb as processTrails,qf as processUrl,bl as qualiexApi,dx as resizeKeepingAspect,Cl as resolveFieldMappings,tv as resolvePageTitle,kb as setFormFieldValues,yd as setupQualiexCore,wb as shouldShowField,Ar as shouldUseDevTokens,xx as signService,Ji as slugify,Ur as smallLogoSrc,Bf as sortByMonthYear,Hf as toQueryString,kc as toggleVariants,Qi as trimTextFields,qx as useActionPlan,Yx as useActionPlanProgress,yv as useActiveModules,sd as useAliasFromUrl,zl as useAuth,Fc as useBaseForm,Cc as useColumnResize,zv as useCreateMultipleLeadersMutation,Lv as useCreateSingleLeaderMutation,Fl as useCrud,rv as useDebounce,Jd as useDerivedContractedModules,Us as useFormField,pv as useHasOpenModal,Cv as useI18nFormatters,Ol as useIsMobile,Mv as useLeadershipApi,Pd as useLocale,jl as useMediaQuery,Xv as useMediaUpload,hv as useModalState,Xd as useModuleAccess,Id as useModuleConfig,ev as useNavigation,bd as usePageMetadata,xd as usePageMetadataContext,av as usePageTitle,sv as usePermissionQuery,Vc as useQualiexUsers,Uv as useRemoveLeaderMutation,fm as useRouteBreadcrumbs,Nv as useRowResize,Vm as useSidebar,dv as useSidebarResize,px as useSignConfig,jv as useSyncSubordinatesMutation,Fv as useUpdateLeaderMutation,lp as useUpdatesNotification,wv as useWizard,_b as validateFields};
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 s,useCallback as o,createContext as l,useContext as c,useRef as d,useEffect as u,memo as m,Component as h,forwardRef as p}from"react";import{Slot as f}from"@radix-ui/react-slot";import{cva as g}from"class-variance-authority";import{clsx as v}from"clsx";import{twMerge as x}from"tailwind-merge";import{getDefaultOptions as b,parseISO as y,isValid as N,format as w}from"date-fns";import{toast as C,Toaster as k}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as _,X as S,ChevronDown as A,ChevronUp as D,Check as P,Loader2 as E,Loader2Icon as T,OctagonXIcon as I,TriangleAlertIcon as M,InfoIcon as R,CircleCheckIcon as L,ChevronRight as z,Circle as F,AlertCircle as U,Search as j,FileX as O,Edit as B,PowerOff as $,Power as V,Trash2 as q,Pencil as W,ToggleRight as H,ToggleLeft as G,Plus as Y,LayoutGrid as K,List as Q,Table2 as X,Columns3 as J,GripVertical as Z,Group as ee,ArrowUp as ae,ArrowDown as te,Target as re,Trophy as ne,Award as ie,Sparkles as se,Flame as oe,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 xe,Save as be,Copy as ye,Share as Ne,Upload as we,Download as Ce,HelpCircle as ke,Info as _e,Bell as Se,Clock as Ae,ArrowRight as De,ArrowLeft as Pe,ChevronLeft as Ee,Minus as Te,Filter as Ie,Bookmark as Me,Book as Re,Video as Le,Music as ze,Image as Fe,Camera as Ue,MapPin as je,Calendar as Oe,Phone as Be,Mail as $e,Settings as Ve,User as qe,Home as We,Heart as He,Star as Ge,ChevronsLeft as Ye,ChevronsRight as Ke,CheckCircle as Qe,AlertTriangle as Xe,RefreshCw as Je,ExternalLink as Ze,NotebookText as ea,Building2 as aa,LogOut as ta,MoreHorizontal as ra,PanelLeft as na,Edit3 as ia,Code as sa,Heading1 as oa,Heading2 as la,Heading3 as ca,Bold as da,Italic as ua,Underline as ma,Strikethrough as ha,ListOrdered as pa,Highlighter as fa,Link as ga,RemoveFormatting as va,Undo as xa,Redo as ba,ImageIcon as ya,FileSpreadsheet as Na,FileImage as wa,ShieldCheck as Ca,Coffee as ka,CheckCheck as _a,Users as Sa,TriangleAlert as Aa,CheckCircle2 as Da,Hourglass as Pa,MoreVertical as Ea,ArrowUpToLine as Ta,Menu as Ia,Crown as Ma,UserPlus as Ra,MessageSquare as La,Smartphone as za,Paperclip as Fa,CloudUpload as Ua,RotateCcw as ja,Layers as Oa,XCircle as Ba}from"lucide-react";import*as $a from"@radix-ui/react-label";import*as Va from"@radix-ui/react-dialog";import*as qa from"@radix-ui/react-separator";import*as Wa from"@radix-ui/react-alert-dialog";import{useFormContext as Ha,FormProvider as Ga,Controller as Ya,appendErrors as Ka,useForm as Qa}from"react-hook-form";import*as Xa from"@radix-ui/react-select";import*as Ja from"@radix-ui/react-checkbox";import*as Za from"@radix-ui/react-dropdown-menu";import*as et from"@radix-ui/react-tooltip";import*as at from"@radix-ui/react-popover";import{useTranslation as tt,initReactI18next as rt,I18nextProvider as nt}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as it from"@radix-ui/react-scroll-area";import{createClient as st}from"@supabase/supabase-js";import{useQueryClient as ot,useQuery as lt,useMutation as ct,QueryClient as dt,QueryClientProvider as ut}from"@tanstack/react-query";import{useSearchParams as mt,useParams as ht,useNavigate as pt,useLocation as ft,Navigate as gt,Link as vt}from"react-router-dom";import*as xt from"@radix-ui/react-context-menu";import*as bt from"@radix-ui/react-toggle-group";import*as yt from"@radix-ui/react-toggle";import*as Nt from"@radix-ui/react-switch";import wt from"i18next";export{default as i18n}from"i18next";import*as Ct from"@radix-ui/react-collapsible";import*as kt from"@radix-ui/react-tabs";import*as _t from"@radix-ui/react-accordion";import*as St from"@radix-ui/react-avatar";import{DayPicker as At}from"react-day-picker";import{Drawer as Dt}from"vaul";import*as Pt from"@radix-ui/react-hover-card";import*as Et from"@radix-ui/react-navigation-menu";import*as Tt from"@radix-ui/react-progress";import*as It from"@radix-ui/react-radio-group";import*as Mt from"react-resizable-panels";import*as Rt from"@radix-ui/react-slider";import*as Lt from"@radix-ui/react-menubar";import*as zt from"recharts";import{ResponsiveContainer as Ft,XAxis as Ut,YAxis as jt,CartesianGrid as Ot,Tooltip as Bt,Legend as $t,BarChart as Vt,Bar as qt,AreaChart as Wt,Area as Ht,LineChart as Gt,Line as Yt,PieChart as Kt,Pie as Qt,Cell as Xt,ComposedChart as Jt}from"recharts";import{useEditor as Zt,EditorContent as er}from"@tiptap/react";import ar from"@tiptap/starter-kit";import tr from"@tiptap/extension-underline";import rr from"@tiptap/extension-link";import{TextStyle as nr}from"@tiptap/extension-text-style";import{Color as ir}from"@tiptap/extension-color";import sr from"@tiptap/extension-highlight";import{useSensors as or,useSensor as lr,PointerSensor as cr,DndContext as dr,closestCenter as ur}from"@dnd-kit/core";import{SortableContext as mr,rectSortingStrategy as hr,useSortable as pr}from"@dnd-kit/sortable";import{z as fr}from"zod";import{validateFieldsNatively as gr,toNestErrors as vr}from"@hookform/resolvers";const xr="ccjfvpnndclajkleyqkc",br={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},yr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function Nr(){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===xr?br:yr}function wr(){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!==xr}const Cr={get oauth(){const e=Nr();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},kr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},_r={debounceDelay:500},Sr=()=>{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},Ar=()=>Sr(),Dr=Sr,Pr=()=>Nr().qualiexApiUrl,Er={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Tr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ir={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Mr={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}`}},Rr=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)}}),Lr=`https://${Nr().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,zr={logo:Ir.isQualiex?`${Lr}/logo-qualiex-white.svg`:`${Lr}/saber-gestao-white.png`,smallLogo:Ir.isQualiex?`${Lr}/logo-forlogic-white.svg`:`${Lr}/small.svg`,favicon:`${Lr}/favicon.png`},Fr=zr.logo,Ur=zr.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=zr.favicon,document.head.appendChild(e)}const jr={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 Or(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Br={date:Or({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Or({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:Or({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},$r={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Vr(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 qr={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:Vr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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 Wr(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 s=i[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(s)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(s));let c;c=e.valueCallback?e.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;return{value:c,rest:a.slice(s.length)}}}function Hr(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 s=e.valueCallback?e.valueCallback(i[0]):i[0];s=t.valueCallback?t.valueCallback(s):s;return{value:s,rest:a.slice(n.length)}}}const Gr={ordinalNumber:Hr({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},Yr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=jr[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:Br,formatRelative:(e,a,t,r)=>$r[e],localize:qr,match:Gr,options:{weekStartsOn:0,firstWeekContainsDate:1}};let Kr={};function Qr(){return Kr}const Xr=6048e5;function Jr(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 Zr(e){const a=Jr(e);return a.setHours(0,0,0,0),a}function en(e){const a=Jr(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 an(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function tn(e){const a=Jr(e),t=function(e,a){const t=Zr(e),r=Zr(a),n=+t-en(t),i=+r-en(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Jr(e),t=an(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function rn(e,a){const t=Qr(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Jr(e),i=n.getDay(),s=(i<r?7:0)+i-r;return n.setDate(n.getDate()-s),n.setHours(0,0,0,0),n}function nn(e){return rn(e,{weekStartsOn:1})}function sn(e){const a=Jr(e),t=a.getFullYear(),r=an(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=nn(r),i=an(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const s=nn(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=s.getTime()?t:t-1}function on(e){const a=Jr(e),t=+nn(a)-+function(e){const a=sn(e),t=an(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),nn(t)}(a);return Math.round(t/Xr)+1}function ln(e,a){const t=Jr(e),r=t.getFullYear(),n=Qr(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=an(e,0);s.setFullYear(r+1,0,i),s.setHours(0,0,0,0);const o=rn(s,a),l=an(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const c=rn(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function cn(e,a){const t=Jr(e),r=+rn(t,a)-+function(e,a){const t=Qr(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=ln(e,a),i=an(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),rn(i,a)}(t,a);return Math.round(r/Xr)+1}function dn(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const un={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return dn("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):dn(t+1,2)},d:(e,a)=>dn(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)=>dn(e.getHours()%12||12,a.length),H:(e,a)=>dn(e.getHours(),a.length),m:(e,a)=>dn(e.getMinutes(),a.length),s:(e,a)=>dn(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return dn(Math.trunc(r*Math.pow(10,t-3)),a.length)}},mn="midnight",hn="noon",pn="morning",fn="afternoon",gn="evening",vn="night",xn={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 un.y(e,a)},Y:function(e,a,t,r){const n=ln(e,r),i=n>0?n:1-n;if("YY"===a){return dn(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):dn(i,a.length)},R:function(e,a){return dn(sn(e),a.length)},u:function(e,a){return dn(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 dn(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 dn(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 un.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 dn(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=cn(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):dn(n,a.length)},I:function(e,a,t){const r=on(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):dn(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):un.d(e,a)},D:function(e,a,t){const r=tn(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):dn(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 dn(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 dn(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 dn(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?hn:0===r?mn: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?gn:r>=12?fn:r>=4?pn:vn,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 un.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):un.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):un.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):un.s(e,a)},S:function(e,a){return un.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return yn(r);case"XXXX":case"XX":return Nn(r);default:return Nn(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return yn(r);case"xxxx":case"xx":return Nn(r);default:return Nn(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+bn(r,":");default:return"GMT"+Nn(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+bn(r,":");default:return"GMT"+Nn(r,":")}},t:function(e,a,t){return dn(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return dn(e.getTime(),a.length)}};function bn(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+dn(i,2)}function yn(e,a){if(e%60==0){return(e>0?"-":"+")+dn(Math.abs(e)/60,2)}return Nn(e,a)}function Nn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+dn(Math.trunc(r/60),2)+a+dn(r%60,2)}const wn=(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"})}},Cn=(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"})}},kn={p:Cn,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return wn(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}}",wn(r,a)).replace("{{time}}",Cn(n,a))}},_n=/^D+$/,Sn=/^Y+$/,An=["D","DD","YY","YYYY"];function Dn(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=Jr(e);return!isNaN(Number(a))}const Pn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,En=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Tn=/^'([^]*?)'?$/,In=/''/g,Mn=/[a-zA-Z]/;function Rn(e,a,t){const r=Qr(),n=t?.locale??r.locale??Yr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Jr(e);if(!Dn(o))throw new RangeError("Invalid time value");let l=a.match(En).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,kn[a])(e,n.formatLong)}return e}).join("").match(Pn).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Ln(e)};if(xn[a])return{isToken:!0,value:e};if(a.match(Mn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const c={firstWeekContainsDate:i,weekStartsOn:s,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return Sn.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return _n.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(An.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,xn[i[0]])(o,i,n.localize,c)}).join("")}function Ln(e){const a=e.match(Tn);return a?a[1].replace(In,"'"):e}function zn(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 Fn(e,a){const t=function(e){jn[e]||(jn[e]=Bn?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 jn[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=Un[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 Un={year:0,month:1,day:2,hour:3,minute:4,second:5};const jn={},On=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")),Bn="06/25/2014, 00:00:00"===On||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===On;function $n(e,a,t,r,n,i,s){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,i,s),o}const Vn=36e5,qn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Wn(e,a,t){if(!e)return 0;let r,n,i=qn.timezoneZ.exec(e);if(i)return 0;if(i=qn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Gn(r)?-r*Vn:NaN;if(i=qn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Gn(r,e)?(n=Math.abs(r)*Vn+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(Yn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Yn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return $n(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Hn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Hn(new Date(n),t);if(a===i)return a;n-=i-a;const s=Hn(new Date(n),t);if(i===s)return i;return Math.max(i,s)}(a,n,e);return-i}return NaN}function Hn(e,a){const t=Fn(e,a),r=$n(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 Gn(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Yn={};const Kn={X:function(e,a,t){const r=Qn(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Zn(r);case"XXXX":case"XX":return Jn(r);default:return Jn(r,":")}},x:function(e,a,t){const r=Qn(t.timeZone,e);switch(a){case"x":return Zn(r);case"xxxx":case"xx":return Jn(r);default:return Jn(r,":")}},O:function(e,a,t){const r=Qn(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+Xn(i,2)}(r,":");default:return"GMT"+Jn(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return zn("short",e,t);default:return zn("long",e,t)}}};function Qn(e,a){const t=e?Wn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Xn(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Jn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Xn(Math.floor(r/60),2)+a+Xn(Math.floor(r%60),2)}function Zn(e,a){if(e%60==0){return(e>0?"-":"+")+Xn(Math.abs(e)/60,2)}return Jn(e,a)}function ei(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 ai=36e5,ti=6e4,ri={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 ni(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=ri.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=ri.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=ri.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=ri.YYY[a],r=ri.YYYYY[a];let n=ri.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=ri.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),s=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=ri.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,ci(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=ri.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=li(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=ri.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return ci(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=ri.Www.exec(e),i)return n=parseInt(i[1],10)-1,di(n)?ii(a,n):new Date(NaN);if(i=ri.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return di(n,e)?ii(a,n,e):new Date(NaN)}return null}(i,n);if(null===s||isNaN(s.getTime()))return new Date(NaN);if(s){const e=s.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=ri.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),ui(a)?a%24*ai:NaN;if(r=ri.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),ui(a,t)?a%24*ai+t*ti:NaN;if(r=ri.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return ui(a,t,e)?a%24*ai+t*ti+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Wn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=ei(new Date(e+n)),t=ei(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function ii(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 si=[31,28,31,30,31,30,31,31,30,31,30,31],oi=[31,29,31,30,31,30,31,31,30,31,30,31];function li(e){return e%400==0||e%4==0&&e%100!=0}function ci(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=li(e);if(r&&t>oi[a])return!1;if(!r&&t>si[a])return!1}return!0}function di(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function ui(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const mi=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function hi(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(mi);if(r){const n=ni(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],s=e.replace(a,"'"+Kn[a[0]](n,a,t)+"'");return i?s.substring(0,r-1)+s.substring(r+1):s},a)}return Rn(e,a,t)}(function(e,a,t){const r=Wn(a,e=ni(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 pi={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"}},fi={date:Or({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:Or({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Or({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},gi={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"},vi={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"},xi={ordinalNumber:(e,a)=>Number(e)+"º",era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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"})},bi={ordinalNumber:Hr({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},yi={code:"es",formatDistance:(e,a,t)=>{let r;const n=pi[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:fi,formatRelative:(e,a,t,r)=>1!==a.getHours()?vi[e]:gi[e],localize:xi,match:bi,options:{weekStartsOn:1,firstWeekContainsDate:1}},Ni={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"}},wi={date:Or({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:Or({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Or({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Ci={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"},ki={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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"})},_i={ordinalNumber:Hr({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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"})},Si={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=Ni[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:wi,formatRelative:(e,a,t,r)=>{const n=Ci[e];return"function"==typeof n?n(a):n},localize:ki,match:_i,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ai=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Di=[{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"}],Pi=[{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"}],Ei="pt-BR",Ti="dd/MM/yyyy HH:mm",Ii="America/Sao_Paulo",Mi=e=>Ai.find(a=>a.value===e),Ri=e=>Di.find(a=>a.value===e),Li=e=>Pi.find(a=>a.value===e),zi=e=>Ai.some(a=>a.value===e),Fi=e=>Di.some(a=>a.value===e),Ui=e=>Pi.some(a=>a.value===e),ji=()=>{if("undefined"==typeof navigator)return Ei;const e=navigator.language;if(zi(e))return e;const a=e.split("-")[0],t=Ai.find(e=>e.value.startsWith(a));return t?.value||Ei},Oi=()=>{if("undefined"==typeof Intl)return Ii;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Ui(e)?e:Ii}catch{return Ii}},Bi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Ti),$i=()=>{const e=ji();return{locale:e,timezone:Oi(),datetimeFormat:Bi(e)}},Vi={"pt-BR":Si,"en-US":Yr,"es-ES":yi},qi=(e,a=Ti,t=Ii,r=Ei)=>{if(!e)return"";const n=y(e);if(!N(n))return"Data inválida";const i=Vi[r]||Si;try{return hi(n,t,a,{locale:i})}catch(s){return hi(n,Ii,a,{locale:i})}},Wi=(e,a=Ei,t=Ii)=>{if(!e)return"";const r=y(e);if(!N(r))return"Data inválida";const n=Vi[a]||Si;try{return hi(r,t,"PP",{locale:n})}catch(i){return hi(r,Ii,"PP",{locale:n})}},Hi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Gi(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{C.info("Link copiado para a área de transferência")})}function Yi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Ki(...e){return x(v(e))}const Qi=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Qi);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Qi(r);return a}return e},Xi=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Ji=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Zi=g("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"}}),es=r.forwardRef(({className:a,variant:t,size:r,asChild:n=!1,...i},s)=>e(n?f:"button",{className:Ki(Zi({variant:t,size:r,className:a})),ref:s,...i}));es.displayName="Button";const as=n.forwardRef(({className:a,children:t,variant:r="action",...n},i)=>e(es,{ref:i,variant:r,size:"icon",className:Ki("h-8 w-8",a),...n,children:t||e(_,{size:16})}));as.displayName="ActionButton";const ts=r.forwardRef(({className:a,type:t,...r},n)=>e("input",{type:t,className:Ki("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}));ts.displayName="Input";const rs=g("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ns=r.forwardRef(({className:a,...t},r)=>e($a.Root,{ref:r,className:Ki(rs(),a),...t}));ns.displayName=$a.Root.displayName;const is=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));is.displayName="Card";const ss=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex flex-col space-y-1.5 p-6",a),...t}));ss.displayName="CardHeader";const os=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Ki("text-2xl font-semibold leading-none tracking-tight",a),...t}));os.displayName="CardTitle";const ls=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));ls.displayName="CardDescription";const cs=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("p-6 pt-0",a),...t}));cs.displayName="CardContent";const ds=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex items-center p-6 pt-0",a),...t}));ds.displayName="CardFooter";const us=r.forwardRef(({className:a,orientation:t="horizontal",decorative:r=!0,...n},i)=>e(qa.Root,{ref:i,decorative:r,orientation:t,className:Ki("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...n}));us.displayName=qa.Root.displayName;const ms=Wa.Root,hs=Wa.Trigger,ps=Wa.Portal,fs=r.forwardRef(({className:a,...t},r)=>e(Wa.Overlay,{className:Ki("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}));fs.displayName=Wa.Overlay.displayName;const gs=r.forwardRef(({className:t,...r},n)=>a(ps,{children:[e(fs,{}),e(Wa.Content,{ref:n,className:Ki("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})]}));gs.displayName=Wa.Content.displayName;const vs=({className:a,...t})=>e("div",{className:Ki("flex flex-col space-y-2 text-center sm:text-left",a),...t});vs.displayName="AlertDialogHeader";const xs=({className:a,...t})=>e("div",{className:Ki("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});xs.displayName="AlertDialogFooter";const bs=r.forwardRef(({className:a,...t},r)=>e(Wa.Title,{ref:r,className:Ki("text-lg font-semibold",a),...t}));bs.displayName=Wa.Title.displayName;const ys=r.forwardRef(({className:a,...t},r)=>e(Wa.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));ys.displayName=Wa.Description.displayName;const Ns=r.forwardRef(({className:a,...t},r)=>e(Wa.Action,{ref:r,className:Ki(Zi(),a),...t}));Ns.displayName=Wa.Action.displayName;const ws=r.forwardRef(({className:a,...t},r)=>e(Wa.Cancel,{ref:r,className:Ki(Zi({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));ws.displayName=Wa.Cancel.displayName;const Cs=Va.Root,ks=Va.Trigger,_s=Va.Portal,Ss=Va.Close,As=r.forwardRef(({className:a,...t},r)=>e(Va.Overlay,{ref:r,className:Ki("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}));As.displayName=Va.Overlay.displayName;const Ds={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"}},Ps=r.forwardRef(({className:t,children:n,size:i,variant:s="informative",isDirty:o,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:x,onInteractOutside:b,onEscapeKeyDown:y,...N},w)=>{const[C,k]=r.useState(!1),_=r.useRef(null),A=i??(l||c||d||u||m||h?void 0:"md"),D=A?Ds[A]:{},P={...l??D.width?{width:l??D.width}:{},...c??D.minWidth?{minWidth:c??D.minWidth}:{},...d??D.maxWidth?{maxWidth:d??D.maxWidth}:{},...u??D.height?{height:u??D.height}:{},...m??D.minHeight?{minHeight:m??D.minHeight}:{},...h??D.maxHeight?{maxHeight:h??D.maxHeight}:{},...x},E=r.useCallback(e=>{"form"===s&&o?(_.current=e,k(!0)):e()},[s,o]),T="destructive"!==s;return a(_s,{children:[e(As,{}),a(Va.Content,{ref:w,className:Ki("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:P,onInteractOutside:e=>{"form"!==s&&"destructive"!==s?b?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==s)return"form"===s&&o?(e.preventDefault(),void E(()=>{y?.(e)})):void y?.(e);e.preventDefault()},...N,children:[n,T&&a(Va.Close,{onClick:e=>{"form"===s&&o&&(e.preventDefault(),E(()=>{const a=e.target.closest("[data-radix-collection-item]");a&&a.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e(ms,{open:C,onOpenChange:k,children:a(gs,{children:[a(vs,{children:[e(bs,{children:p}),e(ys,{children:f})]}),a(xs,{children:[e(ws,{onClick:()=>{k(!1),_.current=null},children:g}),e(Ns,{onClick:()=>{k(!1),_.current?.(),_.current=null},children:v})]})]})})]})});Ps.displayName=Va.Content.displayName;const Es=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Ki("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(us,{className:"mt-2"})]});Es.displayName="DialogHeader";const Ts=({className:a,...t})=>e("div",{className:Ki("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Ts.displayName="DialogBody";const Is=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{className:"mb-4"}),e("div",{className:Ki("flex flex-row justify-end gap-2",t),...n,children:r})]});Is.displayName="DialogFooter";const Ms=r.forwardRef(({className:a,...t},r)=>e(Va.Title,{ref:r,className:Ki("text-lg font-semibold leading-none tracking-tight",a),...t}));Ms.displayName=Va.Title.displayName;const Rs=r.forwardRef(({className:a,...t},r)=>e(Va.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Rs.displayName=Va.Description.displayName;const Ls=Ga,zs=r.createContext({}),Fs=({...a})=>e(zs.Provider,{value:{name:a.name},children:e(Ya,{...a})}),Us=()=>{const e=r.useContext(zs),a=r.useContext(js),{getFieldState:t,formState:n}=Ha(),i=t(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=a;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},js=r.createContext({}),Os=r.forwardRef(({className:a,...t},n)=>{const i=r.useId();return e(js.Provider,{value:{id:i},children:e("div",{ref:n,className:Ki("space-y-2",a),...t})})});Os.displayName="FormItem";const Bs=r.forwardRef(({className:a,...t},r)=>{const{error:n,formItemId:i}=Us();return e(ns,{ref:r,className:Ki(n&&"text-destructive",a),htmlFor:i,...t})});Bs.displayName="FormLabel";const $s=r.forwardRef(({...a},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=Us();return e(f,{ref:t,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...a})});$s.displayName="FormControl";const Vs=r.forwardRef(({className:a,...t},r)=>{const{formDescriptionId:n}=Us();return e("p",{ref:r,id:n,className:Ki("text-sm text-muted-foreground",a),...t})});Vs.displayName="FormDescription";const qs=r.forwardRef(({className:a,children:t,...r},n)=>{const{error:i,formMessageId:s}=Us(),o=i?String(i?.message):t;return o?e("p",{ref:n,id:s,className:Ki("text-sm font-medium text-destructive",a),...r,children:o}):null});qs.displayName="FormMessage";const Ws=Xa.Root,Hs=Xa.Group,Gs=Xa.Value,Ys=r.forwardRef(({className:t,children:r,...n},i)=>a(Xa.Trigger,{ref:i,className:Ki("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(Xa.Icon,{asChild:!0,children:e(A,{className:"h-4 w-4 opacity-50"})})]}));Ys.displayName=Xa.Trigger.displayName;const Ks=r.forwardRef(({className:a,...t},r)=>e(Xa.ScrollUpButton,{ref:r,className:Ki("flex cursor-default items-center justify-center py-1",a),...t,children:e(D,{className:"h-4 w-4"})}));Ks.displayName=Xa.ScrollUpButton.displayName;const Qs=r.forwardRef(({className:a,...t},r)=>e(Xa.ScrollDownButton,{ref:r,className:Ki("flex cursor-default items-center justify-center py-1",a),...t,children:e(A,{className:"h-4 w-4"})}));Qs.displayName=Xa.ScrollDownButton.displayName;const Xs=r.forwardRef(({className:t,children:r,position:n="popper",container:i,collisionBoundary:s,...o},l)=>e(Xa.Portal,{container:i,children:a(Xa.Content,{ref:l,className:Ki("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:s,...o,children:[e(Ks,{}),e(Xa.Viewport,{className:Ki("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Qs,{})]})}));Xs.displayName=Xa.Content.displayName;const Js=r.forwardRef(({className:a,...t},r)=>e(Xa.Label,{ref:r,className:Ki("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Js.displayName=Xa.Label.displayName;const Zs=r.forwardRef(({className:t,children:r,...n},i)=>a(Xa.Item,{ref:i,className:Ki("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(Xa.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),e(Xa.ItemText,{children:r})]}));Zs.displayName=Xa.Item.displayName;const eo=r.forwardRef(({className:a,...t},r)=>e(Xa.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));eo.displayName=Xa.Separator.displayName;const ao=r.forwardRef(({className:a,...t},r)=>e(Ja.Root,{ref:r,className:Ki("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:Ki("flex items-center justify-center text-current"),children:e(P,{className:"h-4 w-4"})})}));ao.displayName=Ja.Root.displayName;const to=r.forwardRef(({className:a,...t},r)=>e("textarea",{className:Ki("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}));to.displayName="Textarea";const ro=g("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"}}),no=r.forwardRef(({className:a,variant:t,...r},n)=>e("div",{ref:n,className:Ki(ro({variant:t}),a),...r}));no.displayName="Badge";const io={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function so({size:a="md",className:t}){return e(E,{className:Ki("animate-spin text-muted-foreground",io[a],t)})}function oo({isLoading:r,children:n,className:i,type:s="spinner",size:o="md"}){return r?"overlay"===s?a("div",{className:Ki("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(so,{size:o})})]}):e("div","skeleton"===s?{className:Ki("animate-pulse",i),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Ki("flex items-center justify-center py-8",i),children:e(so,{size:o})}):e(t,{children:n})}const lo=({...a})=>e(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(L,{className:"h-4 w-4"}),info:e(R,{className:"h-4 w-4"}),warning:e(M,{className:"h-4 w-4"}),error:e(I,{className:"h-4 w-4"}),loading:e(T,{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}),co=Za.Root,uo=Za.Trigger,mo=Za.Group,ho=Za.Portal,po=Za.Sub,fo=Za.RadioGroup,go=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(Za.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));go.displayName=Za.SubTrigger.displayName;const vo=r.forwardRef(({className:a,...t},r)=>e(Za.SubContent,{ref:r,className:Ki("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}));vo.displayName=Za.SubContent.displayName;const xo=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(Za.Portal,{children:e(Za.Content,{ref:n,sideOffset:t,className:Ki("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})}));xo.displayName=Za.Content.displayName;const bo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Za.Item,{ref:n,className:Ki("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}));bo.displayName=Za.Item.displayName;const yo=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(Za.CheckboxItem,{ref:s,className:Ki("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(Za.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),r]}));yo.displayName=Za.CheckboxItem.displayName;const No=r.forwardRef(({className:t,children:r,...n},i)=>a(Za.RadioItem,{ref:i,className:Ki("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(Za.ItemIndicator,{children:e(F,{className:"h-2 w-2 fill-current"})})}),r]}));No.displayName=Za.RadioItem.displayName;const wo=r.forwardRef(({className:a,inset:t,...r},n)=>e(Za.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));wo.displayName=Za.Label.displayName;const Co=r.forwardRef(({className:a,...t},r)=>e(Za.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));Co.displayName=Za.Separator.displayName;const ko=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest opacity-60",a),...t});ko.displayName="DropdownMenuShortcut";const _o=({delayDuration:a=300,...t})=>e(et.Provider,{delayDuration:a,...t}),So=et.Root,Ao=et.Trigger,Do=r.forwardRef(({className:a,sideOffset:t=4,...r},n)=>e(et.Content,{ref:n,sideOffset:t,className:Ki("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}));Do.displayName=et.Content.displayName;const Po=r.forwardRef(({children:t,disabledReason:r,className:n},i)=>{const s=e(bo,{ref:i,className:Ki("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(_o,{delayDuration:100,children:a(So,{children:[e(Ao,{asChild:!0,children:e("div",{className:"w-full",children:s})}),e(Do,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):s});Po.displayName="DisabledMenuItem";const Eo=at.Root,To=at.Trigger,Io=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,container:n,...i},s)=>e(at.Portal,{container:n,children:e(at.Content,{ref:s,align:t,sideOffset:r,className:Ki("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})}));Io.displayName=at.Content.displayName;const Mo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Mo.displayName="Command";const Ro=({children:a,...t})=>e("div",{...t,children:e(Mo,{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})}),Lo=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:Ki("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})}));Lo.displayName="CommandInput";const zo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));zo.displayName="CommandList";const Fo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("py-6 text-center text-sm text-muted-foreground",a),...t}));Fo.displayName="CommandEmpty";const Uo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("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}));Uo.displayName="CommandGroup";const jo=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("-mx-1 h-px bg-border",a),...t}));jo.displayName="CommandSeparator";const Oo=r.forwardRef(({className:a,disabled:t,onSelect:r,value:n,...i},s)=>e("div",{ref:s,className:Ki("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}));Oo.displayName="CommandItem";const Bo=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function $o({className:a,...t}){return e("div",{className:Ki("animate-pulse rounded-md bg-muted",a),...t})}Bo.displayName="CommandShortcut";const Vo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function qo({multiple:t,options:r,value:n,onChange:o,getOptionValue:l,getOptionLabel:c,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:x,maxDisplayedBadges:b,popoverContainer:y,onOpen:N,onClose:w}){const[C,k]=i(!1),[_,D]=i(""),E=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),T=s(()=>{if(!y)return;let e=y,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},[y]),I=s(()=>{const e=r.map(e=>({original:e,value:l(e),label:c(e)}));return x?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[r,l,c,x]),M=s(()=>{if(!_)return I;const e=Vo(_);return I.filter(a=>Vo(a.label).includes(e))},[I,_]),R=s(()=>I.filter(e=>E.includes(e.value)),[I,E]),L=e=>{k(e),e?N?.():(D(""),w?.())},z=(e,a)=>{a.preventDefault(),a.stopPropagation(),o&&o(t?E.filter(a=>a!==e):"")},F=b?R.slice(0,b):R,U=b&&R.length>b?R.length-b:0;return a("div",{className:Ki("space-y-2",v),children:[u&&a(ns,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Eo,{open:C,onOpenChange:L,modal:!1,children:[e(To,{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(),L(!C))},className:Ki("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",f&&"pointer-events-none opacity-50 cursor-not-allowed",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(t=>a(no,{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&&z(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>z(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),U>0&&a(no,{variant:"outline",className:"gap-1",children:["+",U]})]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(es,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Ki("w-full justify-between min-h-10 h-auto",0===R.length&&"text-muted-foreground"),children:[0===R.length?a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),R[0]?.label]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Io,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:T,collisionBoundary:T,children:a(Mo,{children:[a("div",{className:"relative",children:[e(Lo,{placeholder:p,value:_,onChange:e=>D(e.target.value)}),_&&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:()=>D(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(zo,{children:0===r.length?e(Fo,{children:h}):0===M.length?e(Fo,{children:"Nenhum resultado encontrado"}):e(Uo,{children:M.map(r=>a(Oo,{value:r.value,onSelect:()=>(e=>{if(o)if(t){const a=E.includes(e)?E.filter(a=>a!==e):[...E,e];o(a)}else o(e),k(!1)})(r.value),className:"cursor-pointer",children:[e(P,{className:Ki("mr-2 h-4 w-4",E.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Wo({multiple:t=!1,options:r,items:n,value:i,onChange:s,onValueChange:o,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:x,className:b,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k}){const{t:_}=tt(),S=r||n||[],A=o||s,D=d||_("select_placeholder","Selecione..."),P=h||_("no_results","Nenhum resultado encontrado"),E=p||_("search_placeholder","Pesquisar...");if(v)return a("div",{className:Ki("space-y-2",b),children:[u&&a(ns,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($o,{className:"h-10 w-full"})]});const T="string"==typeof x?x:x instanceof Error?x.message:x?_("error_loading","Erro ao carregar"):void 0;return T?a("div",{className:Ki("space-y-2",b),children:[u&&a(ns,{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(U,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:T})]})]}):e(qo,{multiple:t,options:S,value:i||(t?[]:""),onChange:A,getOptionValue:l,getOptionLabel:c,placeholder:D,label:u,icon:m,emptyMessage:P,searchPlaceholder:E,disabled:f,required:g,className:b,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:C,onClose:k})}const Ho=r.forwardRef(({className:t,children:r,...n},i)=>a(it.Root,{ref:i,className:Ki("relative overflow-hidden",t),...n,children:[e(it.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(Go,{}),e(it.Corner,{})]}));Ho.displayName=it.Root.displayName;const Go=r.forwardRef(({className:a,orientation:t="vertical",...r},n)=>e(it.ScrollAreaScrollbar,{ref:n,orientation:t,className:Ki("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(it.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Go.displayName=it.ScrollAreaScrollbar.displayName;const Yo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ko(e,a){if(!a)return null;const t=Yo(a),r=[];for(const n of e){const e=Yo(n.label).includes(t),i=n.children?Ko(n.children,a):null,s=i&&i.length>0;(e||s)&&r.push({...n,children:e?n.children:s?i:n.children})}return r}function Qo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Qo(t.children,a);if(e)return e}}}function Xo({node:t,level:r,expanded:n,onToggleExpand:i,selectedValues:s,onSelect:o}){const l=t.children&&t.children.length>0,c=s.includes(t.value);return a("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":c,className:Ki("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(),o(t.value)},children:[e(P,{className:Ki("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:Ki("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?A:z,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Jo({nodes:r,level:i,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:c}){return e(t,{children:r.map(t=>{const r=s.has(t.value);return a(n.Fragment,{children:[e(Xo,{node:t,level:i,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:c}),r&&t.children&&t.children.length>0&&e(Jo,{nodes:t.children,level:i+1,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:c})]},t.value)})})}function Zo({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:x,maxDisplayedBadges:b,popoverContainer:y,onOpen:N,onClose:w}){const{t:C}=tt(),[k,_]=i(!1),[D,P]=i(""),[E,T]=i(new Set),I=c||C("select_placeholder","Selecione..."),M=m||C("no_results","Nenhum resultado encontrado"),R=h||C("search_placeholder","Pesquisar..."),L=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),z=s(()=>{if(!y)return;let e=y,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},[y]),F=s(()=>Ko(r,D),[r,D])??r,O=s(()=>D?function(e,a){const t=new Set,r=Yo(a);function n(e){if(!e.children||0===e.children.length)return Yo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Yo(e.label).includes(r)}for(const i of e)n(i);return t}(r,D):new Set,[r,D]),B=D?O:E,$=o(e=>{D||T(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[D]),V=s(()=>L.map(e=>({value:e,label:Qo(r,e)||e})),[L,r]),q=e=>{_(e),e?N?.():(P(""),w?.())},W=o(e=>{if(l)if(t){const a=L.includes(e)?L.filter(a=>a!==e):[...L,e];l(a)}else l(e),_(!1)},[l,t,L]),H=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(t?L.filter(a=>a!==e):"")},G=b?V.slice(0,b):V,Y=b&&V.length>b?V.length-b:0;if(g)return a("div",{className:Ki("space-y-2",x),children:[d&&a(ns,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($o,{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:Ki("space-y-2",x),children:[d&&a(ns,{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(U,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:K})]})]}:{className:Ki("space-y-2",x),children:[d&&a(ns,{children:[d,f&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Eo,{open:k,onOpenChange:q,modal:!1,children:[e(To,{asChild:!0,children:t?a("div",{role:"combobox","aria-expanded":k,"aria-disabled":p,tabIndex:p?-1:0,onKeyDown:e=>{p||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),q(!k))},className:Ki("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===V.length&&"text-muted-foreground"),children:[0===V.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(no,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&H(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>H(t.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),Y>0&&a(no,{variant:"outline",className:"gap-1",children:["+",Y]})]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]}):a(es,{variant:"outline",role:"combobox","aria-expanded":k,disabled:p,className:Ki("w-full justify-between min-h-10 h-auto font-normal",0===V.length&&"text-muted-foreground"),children:[0===V.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"}),V[0]?.label]}),e(A,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Io,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:z,collisionBoundary:z,children:[a("div",{className:"flex items-center border-b px-3",children:[e(j,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:R,value:D,onChange:e=>P(e.target.value)}),D&&e("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:e(S,{className:"h-3.5 w-3.5"})})]}),e(Ho,{className:"max-h-[300px]",children:e("div",{role:"tree",className:"p-1",children:0===F.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(Jo,{nodes:F,level:0,expandedIds:B,onToggleExpand:$,selectedValues:L,onSelect:W})})})]})]})]})}class el{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 s=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),s=!1}const o=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),s=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,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()}}el.LARGE_PAYLOAD_THRESHOLD=1e3;const al="qualiex_access_token",tl="qualiex_id_token",rl="supabase_token",nl="oauth_state",il="oauth_nonce",sl="selected_alias",ol="manual_logout",ll="supabase_project_id",cl={setAccessToken:e=>localStorage.setItem(al,e),getAccessToken:()=>localStorage.getItem(al),setIdToken:e=>localStorage.setItem(tl,e),getIdToken:()=>localStorage.getItem(tl),getSupabaseToken:()=>localStorage.getItem(rl),setOAuthState:e=>sessionStorage.setItem(nl,e),getOAuthState:()=>sessionStorage.getItem(nl),clearOAuthState:()=>sessionStorage.removeItem(nl),setOAuthNonce:e=>sessionStorage.setItem(il,e),getOAuthNonce:()=>sessionStorage.getItem(il),clearOAuthNonce:()=>sessionStorage.removeItem(il),setSelectedAlias:e=>localStorage.setItem(sl,e),getSelectedAlias:()=>localStorage.getItem(sl),clearSelectedAlias:()=>localStorage.removeItem(sl),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:()=>!(!cl.getAccessToken()||!cl.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(ll);return a&&a!==e?(cl.clearAll(),localStorage.setItem(ll,e),!0):(a||localStorage.setItem(ll,e),!1)},setSupabaseToken:e=>{localStorage.setItem(rl,e),cl._clearValidationCache()},areAllTokensValid:()=>{const e=cl.getAccessToken(),a=cl.getIdToken();if(!e||!a)return!1;try{const t=el.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=cl.getAccessToken(),t=cl.getIdToken(),r=cl.getSupabaseToken();return a&&cl.isTokenExpired(a)&&(localStorage.removeItem(al),e=!0),t&&cl.isTokenExpired(t)&&(localStorage.removeItem(tl),e=!0),r&&cl.isTokenExpired(r)&&(localStorage.removeItem(rl),e=!0),e},clearAll:()=>{localStorage.removeItem(al),localStorage.removeItem(tl),localStorage.removeItem(rl),localStorage.removeItem(sl),localStorage.removeItem(ol),sessionStorage.removeItem(nl),sessionStorage.removeItem(il),cl._clearValidationCache()},setManualLogout:()=>localStorage.setItem(ol,"true"),isManualLogout:()=>"true"===localStorage.getItem(ol),clearManualLogout:()=>localStorage.removeItem(ol),isTokenExpired:e=>{try{return el.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{cl._validationCache.isValid=!1,cl._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=cl.getSupabaseToken();if(!e)return!1;if(cl.isTokenExpired(e))return cl._clearValidationCache(),cl._handleExpiredToken(),!1;const a=Date.now();return a-cl._validationCache.timestamp<cl._validationCache.cacheValidityMs?cl._validationCache.isValid:(cl._validationCache.isValid=!0,cl._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>cl.isSupabaseTokenValid()?cl.getSupabaseToken():null,_handleExpiredToken:()=>{cl.clearAll()},extractTokenData:()=>{if(!cl.isSupabaseTokenValid())return null;const e=cl.getSupabaseToken();if(!e)return null;try{const a=el.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 cl._handleExpiredToken(),null}},getCompanyId:e=>{const a=cl.getAccessToken();if(a)try{const t=el.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=cl.extractTokenData();if(t?.companyId)return t.companyId;const r=cl.getIdToken();if(r)try{const a=el.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=[cl.getAccessToken(),cl.getIdToken()];for(const t of a)if(t)try{const a=el.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=cl.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=cl.getIdToken();if(!e)return[];try{const a=el.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 dl=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);C.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){C.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=[]}},ul=import.meta.env.VITE_SUPABASE_URL,ml=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class hl{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ml};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return st(ul,ml,{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 hl.instance||(hl.instance=new hl),hl.instance}getClient(){const e=cl.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!el.isTokenExpired(e)}catch(a){return dl.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function pl(){return hl.getInstance().getClient()}class fl{static async generateToken(e,a,t,r=!1){try{if(!r){const e=cl.getSupabaseToken();if(e&&cl.isSupabaseTokenValid())return e}const n=pl(),{data:i,error:s}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(cl.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 gl{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=cl.getAccessToken(),t=cl.getSelectedAlias();if(!a||!t)return null;const r=await fl.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}gl.regenerationPromise=null,gl.onLogoutCallback=null;class vl{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(cl.clearAll(),window.location.href="/login",!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 xl{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 gl.attemptRegeneration()?(this.isRetrying=!1,!0):(vl.handleError(e),this.isRetrying=!1,!1)}catch(r){return vl.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=cl.getAccessToken();return e?cl.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."}}}xl.isRetrying=!1;const bl=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=xl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=cl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status} ${s.statusText}`);throw e.status=s.status,e.statusCode=s.status,e}return await s.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 dl.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(dl.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 xl.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return dl.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return dl.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 dl.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=cl.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||""})):(dl.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await xl.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 dl.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return dl.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})):(dl.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await xl.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 dl.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return dl.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function yl(e,a){const t=a||Tr.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Nl(e,a){const t=a||Tr.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function wl(e,a){const t=a||Tr.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Cl(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||yl(e.idField),emailField:e.emailField||Nl(e.idField),usernameField:e.usernameField||wl(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:yl(e),emailField:Nl(e),usernameField:wl(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const kl=new Map;class _l{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=kl.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await bl.fetchUsers(e,a);return kl.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(!cl.areAllTokensValid())return e;const t=cl.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Cl(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const s=await this.fetchQualiexUsers(r,n),o=this.indexUsers(s);return e.map(e=>this.enrichEntity(e,i,o))}catch(t){return dl.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Sl=["responsible_name"],Al=e=>Sl.includes(e);function Dl(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:s,schemaName:o,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!cl.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return pl().schema(o).from(n)},u=(e,a,t,r)=>{let n=d().select(s||"*",{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 o=a.includes(".");return o||Al(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,i)=>{const s=Cl(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Al(a)||o||s){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},s=await h.getAll(e);if(!s?.data?.length)return s;const c=await _l.enrichWithUserData(s.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=o?c.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",s=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?s:-s}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",s=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?s:-s}))(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 _l.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},h={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:s,limit:o,additionalFilters:d}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...s}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:s}})(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,s,o),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let x=((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,s,o);if((e=>{if(!c||!l||0===e.length)return!1;const a=Cl(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(x.data)){const e=await m(x.data,t,i,s,o);if(!Array.isArray(e))return e;x={...x,data:e}}return x},async getById(e){const{data:a,error:t}=await d().select(s||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Qi(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={...Qi(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 Pl;const El={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Tl{static async initialize(){try{if(cl.checkProjectMismatch())return{...El};if(!cl.hasAllTokens()||!cl.areAllTokensValid())return cl.clearExpiredTokens(),{...El};const e=cl.getAccessToken(),a=cl.getIdToken();cl.clearManualLogout();const t=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=cl.extractTokenData(),s=i?.alias;let o=null;if(s&&r.some(e=>e.alias===s))o=s;else{const e=cl.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!cl.isSupabaseTokenValid()&&o&&await gl.attemptRegeneration(),!cl.isSupabaseTokenValid())return{...El};let l=null;if(o){const e=cl.getCompanyId(o),a=r.find(e=>e.alias===o);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:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:c,placeName:d,activePlaceId:c,activePlaceName:d}}catch(e){return{...El}}}static async loginDev(){try{const e=pl(),{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=cl.generateOAuthState();cl.setOAuthState(e);const a=cl.generateOAuthNonce();cl.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Cr.oauth.authUrl);r.searchParams.set("client_id",Cr.oauth.clientId),r.searchParams.set("response_type",Cr.oauth.responseType),r.searchParams.set("scope",Cr.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=cl.getAccessToken();e!==r&&cl.clearAll()}if(cl.hasAllTokens()){return cl.getValidSupabaseToken()||await gl.attemptRegeneration(!0),!0}const s=r,o=n;if(!s||!o)throw new Error("Tokens não encontrados na URL de callback");cl.setAccessToken(s),cl.setIdToken(o),cl.clearManualLogout();const l=this.extractAliasFromAccessToken(s);if(l)cl.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");cl.setSelectedAlias(e[0].alias)}if(!await gl.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return cl.clearOAuthState(),cl.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){cl.setManualLogout(),cl.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 el.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}}Pl=Tl,gl.setLogoutCallback(()=>{Pl.logout()});const Il=e=>e?.placeId||null,Ml=e=>e?.placeName||null,Rl=l(void 0),Ll=({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=ot()}catch{}const[l,c]=i(!1),m=d(0),h=o(e=>{r(a=>({...a,...e}))},[]),p=o(e=>{r(a=>({...a,isLoading:e}))},[]),f=o(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=o(async e=>{if(e.alias===t.alias)return;const a=++m.current;try{const i=cl.getAccessToken();if(!i)return;const s=await fl.generateToken(i,e.alias,void 0,!0);if(m.current!==a)return;if(!s)return;cl.setSupabaseToken(s),cl.setSelectedAlias(e.alias);const o=cl.extractTokenData(),l=o?.alias||e.alias,c=o?.companyId||cl.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 bl.fetchActiveUsersMap(l,c);if(m.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Il(e),placeName:Ml(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=o(async()=>{const e=await Tl.processCallback();if(e){const e=await Tl.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]),x=o(async()=>{await Tl.logout(),f(),n&&await n.clear()},[f,n]),b=o(e=>{c(e)},[]),y=o(()=>{},[]),N=o(()=>{n&&n.invalidateQueries()},[n]);u(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(async()=>{if(e)if(cl.areAllTokensValid()){if(!cl.isSupabaseTokenValid())try{await gl.attemptRegeneration()||e&&x()}catch(a){e&&x()}}else e&&x()},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,x]),u(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Tl.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&&(vl.handleError(a),p(!1))}})(),()=>{e=!1}},[h,p,x]);const w=s(()=>({...t,logout:x,processCallback:v,switchUnit:g,availableUnits:t.companies,isSearchVisible:l,setSearchVisible:b,clearSearch:y,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,x,v,g,l,b,y,N]);return e(Rl.Provider,{value:w,children:a})},zl=()=>{const e=c(Rl);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Fl({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:l}){const[c,d]=mt(),u=ot(),{alias:m,userId:h,isAuthenticated:p}=zl(),{t:f}=tt(),g=o(a=>{const t=`${e}_${a}`,r=c.get(t);return r||(c.get(a)||"")},[c,e]),v=g("search"),x=g("sortField")||kr.sorting.defaultField,b=g("sortDirection")||kr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(kr.pagination.defaultPageSize)),w=v,k=s(()=>({search:w,sortField:x,sortDirection:b,page:y,limit:N,...n}),[w,x,b,y,N,n]),_=o(()=>a.getAll(k),[a,k]),S=lt({queryKey:[e,m,h,k],queryFn:_,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=ct({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.created(t)),l?.()},onError:e=>{C.error(`${Mr.error.create(t)}: ${e.message}`)}}),D=ct({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.updated(t)),l?.()},onError:e=>{C.error(`${Mr.error.update(t)}: ${e.message}`)}}),P=ct({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.deleted(t))},onError:e=>{C.error(`${Mr.error.delete(t)}: ${e.message}`)}}),E=o(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]),T=o(e=>{E({search:e,page:1})},[E]),I=o(e=>{E({sortField:e,sortDirection:x===e&&"asc"===b?"desc":"asc",page:1})},[x,b,E]),M=o(e=>{E({page:e})},[E]),R=o(e=>{E({limit:e,page:1})},[E]),L=o(()=>{const a=Object.fromEntries(c),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(r)},[d,c,e]),[z,F]=i([]),U=o(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=o(()=>{F([])},[]),B=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=ct({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),C.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{C.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=o((e,a)=>{const t=a?a(e):e;e.id?D.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,D]);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||kr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:D?.isPending??!1,isDeleting:P?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:x,sortDirection:b,currentPage:y,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>D.mutate({id:e,data:a}),deleteEntity:P.mutate,save:V,handleSearch:T,handleSort:I,handlePageChange:M,handleItemsPerPageChange:R,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Ul(e){const a=Dl({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)=>Fl({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function jl(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 Ol(e=768){return jl(`(max-width: ${e-1}px)`)}const Bl=r.forwardRef(({className:a,...t},r)=>e("table",{ref:r,className:Ki("w-full caption-bottom text-sm table-fixed",a),...t}));Bl.displayName="Table";const $l=r.forwardRef(({className:a,...t},r)=>e("thead",{ref:r,className:Ki("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));$l.displayName="TableHeader";const Vl=r.forwardRef(({className:a,...t},r)=>e("tbody",{ref:r,className:Ki("[&_tr:last-child]:border-0",a),...t}));Vl.displayName="TableBody";const ql=r.forwardRef(({className:a,...t},r)=>e("tfoot",{ref:r,className:Ki("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));ql.displayName="TableFooter";const Wl=r.forwardRef(({className:a,...t},r)=>e("tr",{ref:r,className:Ki("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",a),...t}));Wl.displayName="TableRow";const Hl=r.forwardRef(({className:a,...t},r)=>e("th",{ref:r,className:Ki("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}));Hl.displayName="TableHead";const Gl=r.forwardRef(({className:a,...t},r)=>e("td",{ref:r,className:Ki("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",a),...t}));Gl.displayName="TableCell";const Yl=r.forwardRef(({className:a,...t},r)=>e("caption",{ref:r,className:Ki("mt-4 text-sm text-muted-foreground",a),...t}));function Kl({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($o,{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($o,{className:"h-4 w-20"},t))})},t))})]})})}function Ql({count:t=3}){return e("div",{className:"space-y-4",children:Array.from({length:t}).map((t,r)=>a(is,{children:[a(ss,{children:[e($o,{className:"h-4 w-3/4"}),e($o,{className:"h-3 w-1/2"})]}),e(cs,{children:a("div",{className:"space-y-2",children:[e($o,{className:"h-3 w-full"}),e($o,{className:"h-3 w-2/3"})]})})]},r))})}function Xl({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($o,{className:"h-4 w-24"}),e($o,{className:"h-10 w-full"})]},r)),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e($o,{className:"h-10 w-20"}),e($o,{className:"h-10 w-20"})]})]})}function Jl(){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($o,{className:"h-8 w-8 rounded-full"}),e($o,{className:"h-6 w-32"})]}),a("div",{className:"flex items-center space-x-2",children:[e($o,{className:"h-8 w-8"}),e($o,{className:"h-8 w-24"})]})]})}function Zl(){return e("div",{className:"w-64 border-r bg-muted/10",children:a("div",{className:"p-4",children:[e($o,{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($o,{className:"h-4 w-4"}),e($o,{className:"h-4 w-20"})]},r))})]})})}Yl.displayName="TableCaption";const ec={default:O,search:j,error:U};function ac({icon:t,title:r,description:n,action:i,className:s,variant:o="default"}){const l=!!t,c=ec[o];return a("div",{className:Ki("flex flex-col items-center justify-center py-12 px-4 text-center",s),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(es,{onClick:i.onClick,variant:"outline",children:i.label})]})}function tc({children:t,className:n}){const i=r.useRef(null),[s,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=i.current;e&&o(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 s?e(_o,{delayDuration:300,children:a(So,{children:[e(Ao,{asChild:!0,children:l}),e(Do,{side:"top",className:"max-w-[400px] break-words",children:t})]})}):l}const rc=r.forwardRef(({direction:a,onMouseDown:t,isDragging:r,className:n},i)=>{const s="horizontal"===a;return e("div",{ref:i,onMouseDown:t,className:Ki("absolute z-20 select-none touch-none","transition-colors duration-150",s&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!s&&["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:Ki("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",s?"h-6 w-0.5":"w-6 h-0.5")})})});rc.displayName="TableResizeHandle";const nc=xt.Root,ic=xt.Trigger,sc=xt.Group,oc=xt.Portal,lc=xt.Sub,cc=xt.RadioGroup,dc=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(xt.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));dc.displayName=xt.SubTrigger.displayName;const uc=r.forwardRef(({className:a,...t},r)=>e(xt.SubContent,{ref:r,className:Ki("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}));uc.displayName=xt.SubContent.displayName;const mc=r.forwardRef(({className:a,...t},r)=>e(xt.Portal,{children:e(xt.Content,{ref:r,className:Ki("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})}));mc.displayName=xt.Content.displayName;const hc=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Item,{ref:n,className:Ki("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}));hc.displayName=xt.Item.displayName;const pc=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(xt.CheckboxItem,{ref:s,className:Ki("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(P,{className:"h-4 w-4"})})}),r]}));pc.displayName=xt.CheckboxItem.displayName;const fc=r.forwardRef(({className:t,children:r,...n},i)=>a(xt.RadioItem,{ref:i,className:Ki("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(F,{className:"h-2 w-2 fill-current"})})}),r]}));fc.displayName=xt.RadioItem.displayName;const gc=r.forwardRef(({className:a,inset:t,...r},n)=>e(xt.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",a),...r}));gc.displayName=xt.Label.displayName;const vc=r.forwardRef(({className:a,...t},r)=>e(xt.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-border",a),...t}));vc.displayName=xt.Separator.displayName;const xc=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});xc.displayName="ContextMenuShortcut";const bc=({onEdit:r,onDelete:n,onToggleStatus:i,isActive:s=!0,canDelete:o=!0,customActions:l=[],renderAs:c})=>{const d=[];if(r){const e={icon:B,label:"Editar",onClick:r};d.push(e)}if(l.forEach(e=>{d.push(e)}),i){const e={icon:s?$:V,label:s?"Inativar":"Ativar",onClick:i};d.push(e)}if(o&&n){const e={icon:q,label:"Excluir",onClick:n,destructive:!0};d.push(e)}const u="dropdown"===c?bo:hc;return e(t,{children:d.map((t,r)=>a(u,{onClick:t.onClick,className:Ki("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))})},yc=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(_,{size:12})})}),e(xo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(bc,{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:s,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),Nc=({onEdit:t,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>e(_o,{delayDuration:200,children:a("div",{className:"flex items-center justify-end gap-0.5",children:[t&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t()},children:e(W,{size:14})})}),e(Do,{children:"Editar"})]}),o.map((t,r)=>{const n=t.icon;return a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),t.onClick()},children:e(n,{size:14})})}),e(Do,{children:t.label})]},r)}),i&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:e(s?H:G,{size:14})})}),e(Do,{children:s?"Inativar":"Ativar"})]}),r&&n&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:e(q,{size:14})})}),e(Do,{children:"Excluir"})]})]})}),wc=150;function Cc({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,s]=i(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??wc,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??wc,e),{})}),[l,c]=i(!1),[m,h]=i(null),p=d(0),f=d(0),g=o((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),c(!0),h(e),p.current=a.clientX,f.current=n[e]??wc)},[r,n]);u(()=>{if(!l||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,i=r?.maxWidth??500,o=e=>{const a=e.clientX-p.current,r=Math.max(n,Math.min(i,f.current+a));s(e=>{const a={...e,[m]:r};return t?.(a),a})},d=()=>{c(!1),h(null),a&&s(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",o),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",o),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=o(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??wc,e),{});s(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:l,activeColumn:m,handleMouseDown:g,resetWidths:v}}const kc=g("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"}}),_c=r.forwardRef(({className:a,variant:t,size:r,...n},i)=>e(yt.Root,{ref:i,className:Ki(kc({variant:t,size:r,className:a})),...n}));_c.displayName=yt.Root.displayName;const Sc=r.createContext({size:"default",variant:"default"}),Ac=r.forwardRef(({className:a,variant:t,size:r,children:n,...i},s)=>e(bt.Root,{ref:s,className:Ki("flex items-center justify-center gap-1",a),...i,children:e(Sc.Provider,{value:{variant:t,size:r},children:n})}));Ac.displayName=bt.Root.displayName;const Dc=r.forwardRef(({className:a,children:t,variant:n,size:i,...s},o)=>{const l=r.useContext(Sc);return e(bt.Item,{ref:o,className:Ki(kc({variant:l.variant||n,size:l.size||i}),a),...s,children:t})});Dc.displayName=bt.Item.displayName;const Pc=m(function({onNew:t,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:s="",onSearchChange:o,searchPlaceholder:l,showBulkActions:c=!1,selectedCount:d=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:h,customActions:p=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:x=!1,availableViewModes:b=["table","list","grid"],rightSlot:y,className:N}){const w=d>0,C=t&&n||p.length>0,k=f||x||y,_=i&&o;return C||_||k||c&&w?a("div",{className:Ki("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(es,{onClick:t,children:[e(Y,{size:16,className:"mr-2"}),r||"Novo"]}),p.map((t,r)=>{const n=t.icon;return a(es,{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&&w&&a("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[e(no,{variant:"secondary",className:"mr-1 tabular-nums",children:d}),a(_o,{delayDuration:200,children:[u.length>0?u.map((t,r)=>{const n=t.icon,i=t.disabled;return a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("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(Do,{children:t.label})]},r)}):a(So,{children:[e(Ao,{asChild:!0,children:e(es,{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(Do,{children:"Excluir"})]}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:h,children:e(S,{size:16})})}),e(Do,{children:"Limpar seleção"})]})]})]}),_&&e("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:a("div",{className:"relative w-full",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{type:"text",placeholder:l||"Pesquisar",value:s,onChange:e=>o?.(e.target.value),className:"pl-9 w-full"})]})}),k&&a("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,x&&g&&v&&e(Ac,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:b.map(a=>{const t=(e=>{switch(e){case"table":return X;case"list":return Q;case"grid":return K}})(a);return e(Dc,{value:a,"aria-label":"Visualizar como "+("table"===a?"tabela":"list"===a?"lista":"grade"),children:e(t,{className:"h-4 w-4"})},a)})}),y]})]}):null}),Ec=m(({checked:a,onCheckedChange:t})=>e(ao,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function Tc(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 Ic({columns:e,storageKey:a,enabled:t=!0}){const r=s(()=>e.map(e=>String(e.key)),[e]),[n,l]=i(()=>t&&a?Tc(a)?.hiddenColumns??new Set:new Set),[c,d]=i(()=>{if(!t||!a)return r;const e=Tc(a)?.columnOrder;return e&&e.length>0?e:r}),[m,h]=i(()=>t&&a?Tc(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=o(e=>n.has(e),[n]),v=o(e=>{l(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),x=o(()=>{l(new Set)},[]),b=o(()=>{if(l(new Set),d(r),h([]),f(new Set),a)try{localStorage.removeItem(a)}catch{}},[r,a]),y=o((e,a)=>{d(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),N=o(e=>{f(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),w=o(e=>{h(e),f(new Set)},[]),C=o(e=>{h(a=>a.includes(e)?a:[...a,e])},[]),k=o(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})},[]),_=o((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=o(e=>{h(e?[e]:[]),f(new Set)},[]),D=s(()=>{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]),P=o(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,...s]=t,o=new Map;for(const l of a){const e=String(l[i]??"(vazio)");o.has(e)||o.set(e,[]),o.get(e).push(l)}return Array.from(o.entries()).map(([a,t])=>{const o=n?`${n}|${i}:${a}`:`${i}:${a}`,l=s.length>0?e(t,s,r+1,o):void 0;return{groupKey:o,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,m,0,"")},[m]);return{visibleColumns:D,allColumns:e,isColumnHidden:g,toggleColumn:v,showAllColumns:x,resetColumns:b,columnOrder:c,reorderColumns:y,groupByColumn:S,setGroupByColumn:A,groupByColumns:m,setGroupByColumns:w,addGroupByColumn:C,removeGroupByColumn:k,reorderGroupByColumns:_,getGroupedData:P,collapsedGroups:p,toggleGroupCollapse:N}}function Mc({enabled:e=!1,onReorder:a}){const[t,r]=i(null),[n,l]=i(null),c=o(()=>{r(null),l(null)},[]),d=o((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 s(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:d}),[t,n,d])}function Rc({columns:t,columnOrder:r,isColumnHidden:n,toggleColumn:s,showAllColumns:o,reorderColumns:l,groupByColumn:c,setGroupByColumn:u,groupByColumns:m=[],addGroupByColumn:h,removeGroupByColumn:p,resetColumns:f}){const[g,v]=i(null),[x,b]=i(null),y=d(null),N=new Map(t.map(e=>[String(e.key),e])),w=r.filter(e=>N.has(e)).map(e=>N.get(e)),C=()=>{y.current=null,v(null),b(null)};w.some(e=>n(String(e.key)));const k=w.every(e=>!n(String(e.key)));return a(Eo,{children:[e(To,{asChild:!0,children:e(es,{variant:"outline",size:"icon",className:"h-8 w-8",children:e(J,{size:16})})}),a(Io,{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(_o,{delayDuration:300,children:w.map((t,r)=>{const i=String(t.key),o=n(i),d=!1!==t.hideable,f=!0===t.groupable,N=m.includes(i)||c===i;return a("div",{draggable:!0,onDragStart:()=>(e=>{y.current=e,v(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),b(a)})(e,r),onDrop:()=>(e=>{null!==y.current&&y.current!==e&&l(y.current,e),y.current=null,v(null),b(null)})(r),onDragEnd:C,className:Ki("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",x===r&&"border-t-2 border-primary"),children:[e(Z,{size:14,className:"text-muted-foreground shrink-0"}),e(ao,{checked:!o,onCheckedChange:()=>d&&s(i),disabled:!d,className:"shrink-0"}),e("span",{className:Ki("flex-1 truncate",o&&"text-muted-foreground"),children:t.header}),f&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:Ki("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(ee,{size:14})})}),e(Do,{children:N?"Remover agrupamento":"Agrupar por esta coluna"})]})]},i)})})}),a("div",{className:"border-t px-3 py-2 space-y-1",children:[e(es,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:k?()=>w.filter(e=>!1!==e.hideable).forEach(e=>s(String(e.key))):o,children:k?"Deselecionar todas":"Selecionar todas"}),f&&e(es,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Lc({columns:t,groupByColumns:r,addGroupByColumn:s,removeGroupByColumn:o,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&&s(a)}},className:Ki("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(ee,{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 s=u===r,c=h===r&&u!==r;return a(n.Fragment,{children:[r>0&&e("span",{className:"text-xs text-muted-foreground",children:"›"}),a(no,{variant:"secondary",className:Ki("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",s&&"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(),o(t)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:e(S,{size:12})})]})]},t)}):e("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const zc=({manager:t,columns:r,onEdit:i,onView:o,onToggleStatus:l,onDelete:c,renderActions:d,customRowActions:m,enableBulkActions:h=!1,rowActionsVariant:p="dropdown",onNew:f,newButtonLabel:g,showNewButton:v=!0,customActions:x=[],hideActionBar:b,showActionBar:y=!0,showSearch:N=!1,searchValue:w,onSearchChange:C,searchPlaceholder:k,bulkActions:_=[],onBulkDelete:S,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T=!1,enableColumnResize:I=!0,resizeStorageKey:M,enableColumnManager:R=!0,columnManagerStorageKey:L,enableGrouping:F=!1})=>{const{setSearchVisible:U}=zl(),j=Ol(),O=void 0!==b?!b:y;u(()=>{if(!N)return U(!0),()=>U(!1)},[U,N]);const B=Ic({columns:r,storageKey:L,enabled:R}),$=Mc({enabled:R,onReorder:B.reorderColumns}),V=R?B.visibleColumns:r,{columnWidths:q,isDragging:W,activeColumn:H,handleMouseDown:G}=Cc({columns:V.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=s(()=>(()=>{if(I)return V.map(e=>{const a=q[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=V.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`}})})(),[V,I,q]),K=f||x.length>0||N||h||D||T||R,Q=O&&K,X=S||(()=>{t.bulkDelete?.(t.selectedIds)}),J=a=>e(Gl,{className:"text-center",children:d?d(a):"inline"===p?e("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:e(Nc,{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(yc,{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(mc,{className:"w-[160px]",children:e(bc,{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"})}),ee=R?e(Rc,{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(Ql,{count:3}):0===t.entities.length?e(ac,{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(Pc,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:w,onSearchChange:C,searchPlaceholder:k,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:_,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:x,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:t.entities.map(r=>a(nc,{children:[e(ic,{asChild:!0,children:e(is,{className:Ki("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(cs,{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(Ec,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),a("div",{className:"flex-1",children:[V.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||o||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(r):e(yc,{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 re=F&&B.groupByColumns.length>0?B.getGroupedData(t.entities):null,ne=null!==re,ie=(h?1:0)+V.length+1,se=r=>a(nc,{children:[e(ic,{asChild:!0,children:a(Wl,{className:Ki("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(Gl,{onClick:e=>e.stopPropagation(),children:e(Ec,{checked:t.selectedIds.includes(r.id),onCheckedChange:()=>t.selectItem(r.id)})}),V.map(a=>e(Gl,{className:a.className,children:e(tc,{children:a.render?a.render(r):String(r[a.key]??"")})},String(a.key))),J(r)]})}),Z(r)]},r.id),oe=(t,r)=>t.map(t=>{const i=B.collapsedGroups.has(t.groupKey),s=16*t.level,o=Math.max(30,70-15*t.level);return a(n.Fragment,{children:[e(Wl,{className:Ki("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>B.toggleGroupCollapse(t.groupKey),children:e(Gl,{colSpan:r,className:"py-2 px-4",children:a("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${s}px`},children:[e(i?z:A,{size:16}),e("span",{children:t.groupValue}),a("span",{className:"text-muted-foreground font-normal",children:["(",t.count,")"]})]})})}),!i&&(t.children?oe(t.children,r):t.items.map(se))]},t.groupKey)});return a("div",{className:"flex flex-col h-full",children:[Q&&e(Pc,{onNew:f,newButtonLabel:g,showNewButton:v,showSearch:N,searchValue:w,onSearchChange:C,searchPlaceholder:k,showBulkActions:h,selectedCount:t.selectedIds.length,bulkActions:_,onBulkDelete:X,onClearSelection:t.clearSelection,customActions:x,filters:D,viewMode:P,onViewModeChange:E,showViewToggle:T}),t.isLoading?e(Kl,{rows:5,columns:V.length}):a("div",{className:"flex flex-col h-full overflow-hidden",children:[F&&e(Lc,{columns:r,groupByColumns:B.groupByColumns,addGroupByColumn:B.addGroupByColumn,removeGroupByColumn:B.removeGroupByColumn,reorderGroupByColumns:B.reorderGroupByColumns}),e("div",{className:"flex-1 overflow-auto",children:a(Bl,{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($l,{children:a(Wl,{children:[h&&e(Hl,{className:"w-[50px]",children:e(Ec,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),V.map((r,n)=>{const i=I&&!1!==r.resizable,s=H===String(r.key),o=R?$.getDragProps(n,String(r.key)):{},l=$.dragFromIndex===n,c=$.dragOverIndex===n&&$.dragFromIndex!==n;return a(Hl,{className:Ki(r.className,r.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",R&&$.isDragging&&"cursor-grabbing",l&&"opacity-50",c&&"border-l-2 border-primary"),onClick:r.sortable?()=>t.handleSort(String(r.key)):void 0,...o,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?null:"asc"===t.sortDirection?e(ae,{size:14,className:"ml-1"}):e(te,{size:14,className:"ml-1"}))]}),i&&e(rc,{direction:"horizontal",onMouseDown:e=>G(String(r.key),e),isDragging:s})]},String(r.key));var d}),e(Hl,{className:"w-[50px] text-center",children:ee||"Ações"})]})}),e(Vl,{children:0===t.entities.length?e(Wl,{children:e(Gl,{colSpan:ie,className:"h-32",children:e(ac,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):ne?oe(re,ie):t.entities.map(se)})]})})]})]})};function Fc(e,a,t,r){const[n,o]=i({}),[l,c]=i({}),d=s(()=>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])}),o(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)=>{o(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 Uc=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],jc=({value:t="#3b82f6",onChange:r,label:n,customColorLabel:i="Cor personalizada",presetColorsLabel:s="Cores predefinidas"})=>a("div",{className:"space-y-2",children:[n&&e(ns,{children:n}),a(Eo,{children:[e(To,{asChild:!0,children:a(es,{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(Io,{className:"w-64",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ns,{htmlFor:"color-input",children:i}),e(ts,{id:"color-input",type:"color",value:t,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),a("div",{children:[e(ns,{children:s}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Uc.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))})]})]})})]})]}),Oc={Star:Ge,Heart:He,Home:We,User:qe,Settings:Ve,Mail:$e,Phone:Be,Calendar:Oe,MapPin:je,Camera:Ue,Image:Fe,Music:ze,Video:Le,Book:Re,Bookmark:Me,Search:j,Filter:Ie,Edit:B,Trash2:q,Plus:Y,Minus:Te,Check:P,X:S,ChevronDown:A,ChevronUp:D,ChevronLeft:Ee,ChevronRight:z,ArrowUp:ae,ArrowDown:te,ArrowLeft:Pe,ArrowRight:De,Clock:Ae,Bell:Se,AlertCircle:U,Info:_e,HelpCircle:ke,Download:Ce,Upload:we,Share:Ne,Copy:ye,Save:be,FileText:xe,Folder:ve,FolderOpen:ge,Archive:fe,Lock:pe,Unlock:he,Eye:me,EyeOff:ue,Shield:de,Key:ce,Zap:le,Flame:oe,Sparkles:se,Award:ie,Trophy:ne,Target:re},Bc=({value:t="Star",onChange:r,label:n,searchLabel:s="Pesquisar"})=>{const[o,l]=i(""),c=Object.entries(Oc).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),d=Oc[t]||Ge;return a("div",{className:"space-y-2",children:[n&&e(ns,{children:n}),a(Eo,{children:[e(To,{asChild:!0,children:a(es,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),t]})}),e(Io,{className:"w-80",children:a("div",{className:"space-y-3",children:[a("div",{children:[e(ns,{htmlFor:"icon-search",children:s}),e(ts,{id:"icon-search",placeholder:s,value:o,onChange:e=>l(e.target.value)})]}),e(Ho,{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))})})]})})]})]})},$c=r.forwardRef(({className:a,...t},r)=>e(Nt.Root,{className:Ki("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(Nt.Thumb,{className:Ki("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")})}));$c.displayName=Nt.Root.displayName;const Vc=(e={})=>{const{user:a,alias:t}=zl(),{enabled:r=!0}=e;return lt({queryKey:["qualiex-users",t],queryFn:()=>bl.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},qc=({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:x,onOpen:b,onClose:y})=>{const{data:N=[],isLoading:w,error:C}=Vc({enabled:h}),k=s(()=>g?N.filter(g):N,[N,g]),_=s(()=>{const e=a?Array.isArray(a)?a:[a]:[];if(0===e.length)return k;const t=new Set(k.map(e=>e.userId||e.id||"")),r=e.filter(e=>e&&!t.has(e));if(0===r.length)return k;const n=r.map(e=>({userId:e,id:e,userName:"[Usuário inativo]",userEmail:""}));return[...k,...n]},[k,a]),S=o(e=>{if("custom"===p&&f)return f(e);const a=e.userName||"";switch(p){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[p,f]);return e(Wo,{multiple:r,value:a??(r?[]:""),onChange:t,options:_,isLoading:w,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:x,onOpen:b,onClose:y})};function Wc({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||""),x=d(null),[b,y]=i(null),N=o(e=>{x.current=e,y(e)},[]),w=s(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:k,updateField:_,handleSubmit:S}=Fc(w,l,void 0,m),A=s(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),D=s(()=>{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(()=>{D!==g&&v(D)},[D,g]);const P=A.find(e=>e.id===D),E=t=>{const r=(t.computedValue,C[t.name]),n=void 0!==r?r:"",i=k[t.name];switch(t.type){case"group":const r="horizontal"===t.layout,s=r?`flex gap-3 w-full ${t.className||""}`:"space-y-3",o=r?Ki("space-y-2 w-full",t.wrapperClassName):Ki("space-y-2",t.className,t.wrapperClassName);return a("div",{className:o,children:[t.label,e("div",{className:s,children:t.fields?.map(e=>E(e))})]},t.name);case"user-select":return a("div",{className:`space-y-2 ${t.className||""}`,children:[a(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(qc,{value:n||"",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(to,{id:t.name,value:n||"",onChange:e=>{_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ws,{value:String(n),onValueChange:e=>{_(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e(Ys,{className:`${i?"border-destructive":""} ${t.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Gs,{placeholder:t.placeholder})}),e(Xs,{children:t.options?.map(a=>e(Zs,{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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Wo,{options:t.options||[],value:Array.isArray(n)?n:[],onChange:e=>_(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:i,popoverContainer:b,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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"date",value:String(n),onChange:e=>_(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:Ki("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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"color",value:n||t.defaultValue||"#000000",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(jc,{value:n||t.defaultValue||"#3b82f6",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Bc,{value:n||t.defaultValue||"Star",onChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{_(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:i,popoverContainer:b,...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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const a=e.target.value,r=""===a?null:Number(a);_(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(ao,{id:t.name,checked:!!n,onCheckedChange:e=>_(t.name,e),disabled:t.disabled}),a(ns,{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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e($c,{id:t.name,checked:!!n,onCheckedChange:e=>_(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(ns,{htmlFor:t.name,children:[t.label,t.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(ts,{id:t.name,type:"text",value:n||"",onChange:e=>{_(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)}},T=o(()=>{if(!P)return null;if(P.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(P.component){const a=P.component;return e(a,{formData:C,updateField:_,errors:k,users:f,disabled:P.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:P.fields.map(E)})},[P,C,_,k,f,E]),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(es,{variant:D===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:[T(),a("div",{className:"flex justify-end space-x-2 pt-4",children:[e(es,{type:"button",variant:"outline",onClick:u,children:"Cancelar"}),e(es,{type:"submit",disabled:p,children:h||"Salvar"})]})]})})]});return e(Cs,{open:m,onOpenChange:e=>{!1===e&&!0===m&&u()},children:a(Ps,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[a(Es,{showSeparator:!0,children:[e(Ms,{children:t}),e(Rs,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function Hc({currentPage:r,totalPages:n,totalItems:i,itemsPerPage:s,onPageChange:o,onItemsPerPageChange:l,variant:c="full"}){const{t:d}=tt();if(0===i)return null;const u=(r-1)*s+1,m=Math.min(r*s,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(Ws,{value:String(s),onValueChange:e=>l(Number(e)),children:[e(Ys,{className:"h-8 w-[70px]",children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"10",children:"10"}),e(Zs,{value:"25",children:"25"}),e(Zs,{value:"50",children:"50"}),e(Zs,{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(es,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ye,{size:16})}),e(es,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ee,{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(es,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e(z,{size:16})}),e(es,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ke,{size:16})})]})]})}function Gc({manager:a}){return e(Hc,{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 Yc={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Kc={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Qc={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Xc({children:a,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:s=!1,className:o}){return e("div",{className:Ki("flex","column"===t?"flex-col":"flex-row",Yc[r],Kc[n],Qc[i],s&&"flex-wrap",o),children:a})}function Jc({manager:r,filters:n,inline:i=!1}){const{isSearchVisible:s}=zl(),o=r.searchTerm,l=a(t,{children:[n.some(e=>"search"===e.type)&&!s&&a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(ts,{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(Ws,{value:t.value||"",onValueChange:e=>t.onChange?.(e),children:[e(Ys,{className:"w-[180px]",children:e(Gs,{placeholder:t.placeholder})}),e(Xs,{children:t.options.map(a=>e(Zs,{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}`)}),o&&a(es,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?e("div",{className:"flex items-center gap-2",children:l}):e(Xc,{direction:"column",gap:"md",className:"mb-6",children:e(Xc,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:l})})}function Zc({manager:t,config:r,formSections:n,onSave:s,onToggleStatus:o,defaultSort:l}){t&&t.queryKey;const{setSearchVisible:c}=zl(),[d,m]=mt(),[h,p]=i(!1),[f,g]=i(null),[v,x]=i({isOpen:!1,entityId:null,entityName:""}),[b,y]=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,w="function"==typeof t?.deleteEntity?e=>{x({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,C=()=>{x({isOpen:!1,entityId:null,entityName:""})},k=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,_=(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(Pc,{onNew:()=>{r.onNew?r.onNew():(g(null),p(!0))},newButtonLabel:r.newButtonLabel,showNewButton:k,showSearch:r.showSearch,searchValue:t.searchTerm,onSearchChange:t.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:t.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{y({isOpen:!0,count:t.selectedIds.length})},onClearSelection:t.clearSelection,customActions:_,filters:r.filters&&r.filters.length>0?e(Jc,{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(zc,{manager:t,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:o,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(Gc,{manager:t})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&e(Wc,{open:h,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{s(e),p(!1),g(null)},onCancel:()=>{p(!1),g(null)},isLoading:t.isLoading,submitButtonText:f?"Atualizar":"Criar"}),e(Cs,{open:v.isOpen,onOpenChange:C,children:a(Ps,{size:"sm",variant:"destructive",children:[e(Es,{showSeparator:!0,children:e(Ms,{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(Is,{children:[e(es,{variant:"outline",onClick:C,children:"Cancelar"}),e(es,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof t?.deleteEntity&&(t.deleteEntity(v.entityId),x({isOpen:!1,entityId:null,entityName:""}))},disabled:t.isDeleting,children:t.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(Cs,{open:b.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:a(Ps,{size:"sm",variant:"destructive",children:[e(Es,{showSeparator:!0,children:e(Ms,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:a("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.count})," ",1===b.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),e(es,{variant:"destructive",onClick:()=>{t.bulkDelete?.(t.selectedIds),y({isOpen:!1,count:0})},disabled:t.isBulkDeleting,children:t.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function ed(a){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:s,onToggleStatus:o}=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:s||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(Zc,{manager:l,config:c,formSections:n.formSections,onSave:i,onToggleStatus:o,defaultSort:n.defaultSort})}}function ad(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 td(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:nd(e),label:nd(e),...rd(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 rd(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 nd(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const id=({children:r})=>{const{isAuthenticated:i,isLoading:s}=zl();if(n.useEffect(()=>{if(s)return;if(i)return;if(cl.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=Ar(),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 Tl.loginDev():Tl.loginProd()})()},[i,s]),s&&!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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Carregando..."})}),a(cs,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Processando..."})}),a(cs,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Iniciando..."})}),a(cs,{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:Ar()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(t,{children:r})};function sd(e={}){const{paramName:a="alias"}=e,t=ht(),{alias:r,companies:n}=zl(),i=t[a]||null;return s(()=>{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 od({children:r,paramName:n="alias"}){const s=pt(),l=ft(),c=ht(),{alias:m,isAuthenticated:h,isLoading:p,switchUnit:f}=zl(),{urlAlias:g,isAliasMismatch:v,isValidAlias:x,isMissing:b,matchedCompany:y}=sd({paramName:n}),[N,w]=i(!1),C=d(!1),k=n in c,_=o(e=>{const a=c[n],{pathname:t,search:r,hash:i}=l;if(a){const n=t.split("/"),s=n.findIndex(e=>e===a);if(s>=0)return n[s]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[c,n,l]);return u(()=>{if(k&&!p&&h&&m&&!C.current)if(b)s(_(m),{replace:!0});else if(!g||x){if(v&&y&&!C.current){(async()=>{C.current=!0,w(!0);try{await f(y)}catch(e){m&&s(_(m),{replace:!0})}finally{C.current=!1,w(!1)}})()}}else s(_(m),{replace:!0})},[k,p,h,m,b,g,x,v,y,f,_,s]),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(so,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):e(t,{children:r})}function ld(){const{alias:a}=zl(),{pathname:t,search:r,hash:n}=ft();return a?e(gt,{to:`/${a}${t}${r}${n}`,replace:!0}):null}const cd=g("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"}}),dd={info:_e,warning:_e,danger:Xe,success:Qe},ud=r.forwardRef(({className:t,variant:r="info",showIcon:n=!0,children:i,...s},o)=>{const l=dd[r||"info"];return a("div",{ref:o,role:"alert",className:Ki(cd({variant:r}),t),...s,children:[n&&e(l,{className:"h-4 w-4"}),i]})});ud.displayName="Alert";const md=r.forwardRef(({className:a,...t},r)=>e("h5",{ref:r,className:Ki("mb-1 font-medium leading-none tracking-tight",a),...t}));md.displayName="AlertTitle";const hd=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("text-sm [&_p]:leading-relaxed",a),...t}));hd.displayName="AlertDescription";const pd=()=>{const{processCallback:r}=zl(),n=pt(),[s,o]=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 o("Falha na autenticação. Tente novamente.")}catch(e){localStorage.removeItem("auth_return_url"),o(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r,n]);const d=async()=>{c(!0),o(null);try{await r()||o("Falha na autenticação. Tente novamente.")}catch(e){o(e?.message||"Erro ao tentar novamente.")}finally{c(!1)}},m=()=>{window.location.href="/"};return e("div",s?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:a(os,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(U,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),a(cs,{className:"space-y-4",children:[e(ud,{variant:"danger",children:e(hd,{children:s})}),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(es,{onClick:d,disabled:l,className:"flex-1",children:a(t,l?{children:[e(so,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Je,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(es,{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(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),a(cs,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(so,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},fd=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:a(is,{className:"w-full max-w-md",children:[e(ss,{className:"text-center",children:e(os,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),a(cs,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(es,{onClick:async()=>{Ar()?await Tl.loginDev():Tl.loginProd()},className:"w-full",size:"lg",children:Ar()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),gd=l(void 0);function vd({children:a,actions:t}){const[r,n]=i({}),[l,c]=i(t);u(()=>{c(t)},[t]);const d=o(()=>n({}),[]),m=s(()=>({metadata:r,setMetadata:n,clearMetadata:d,headerActions:l,setHeaderActions:c}),[r,d,l]);return e(gd.Provider,{value:m,children:a})}function xd(){const e=c(gd);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function bd(e){const{setMetadata:a,clearMetadata:t}=xd(),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 yd(e){return{queryClient:e.queryClient||new dt({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Nd={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"},wd={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"},Cd={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 kd(e,a){wt.addResourceBundle(e,"app",a,!0,!0)}wt.use(rt).init({resources:{"pt-BR":{core:Nd},"en-US":{core:wd},"es-ES":{core:Cd}},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 _d=l(void 0),Sd={locale:Ei,timezone:Ii,datetimeFormat:Ti},Ad=async()=>{},Dd=({children:a})=>e(_d.Provider,{value:{...Sd,setLocale:Ad,setTimezone:Ad,setDatetimeFormat:Ad,isLoading:!1},children:a}),Pd=()=>{const e=c(_d);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},Ed=l({moduleAlias:null});function Td({moduleAlias:a=null,children:t}){return e(Ed.Provider,{value:{moduleAlias:a},children:t})}function Id(){return c(Ed)}const Md=Ct.Root,Rd=Ct.CollapsibleTrigger,Ld=Ct.CollapsibleContent;class zd extends h{constructor(e){super(e),this.copyErrorDetails=()=>{const e=dl.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),C.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;dl.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=dl.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:a(is,{className:"w-full max-w-2xl",children:[a(ss,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Xe,{className:"h-12 w-12 text-destructive"})}),e(os,{children:"Algo deu errado"})]}),a(cs,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),a(Md,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Rd,{asChild:!0,children:a(es,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(A,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),a(Ld,{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(Ho,{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(es,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(ye,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(es,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Fd=kt.Root,Ud=r.forwardRef(({className:a,...t},r)=>e(kt.List,{ref:r,className:Ki("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Ud.displayName=kt.List.displayName;const jd=r.forwardRef(({className:a,...t},r)=>e(kt.Trigger,{ref:r,className:Ki("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}));jd.displayName=kt.Trigger.displayName;const Od=r.forwardRef(({className:a,...t},r)=>e(kt.Content,{ref:r,className:Ki("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));function Bd({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 $d({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 Vd({educaUrl:t="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i}){const s=Yi(t||n||"https://educacao.sabergestao.com.br/{alias}/fe",i);return a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{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:s,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",e(Ze,{className:"h-3.5 w-3.5"})]})]}),e(Bd,{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(Ze,{className:"h-3.5 w-3.5"})]})]}),e($d,{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(Ze,{className:"h-3.5 w-3.5"})]})]}),e(ea,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}Od.displayName=kt.Content.displayName;const qd=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias={alias}"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias={alias}"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function Wd({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:Ki("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 Hd(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 Gd({modules:t,onModuleClick:r,contractedModules:n,onModuleInterest:s}){const o=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=Hd(d,o),p=Hd(m,o),f=(e,a)=>{a?r?.(e):s?.(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(Wd,{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(Wd,{module:a,onClick:()=>f(a,!1)},a.name))})]})]})}function Yd({onModuleClick:t,contractedModules:r,onModuleInterest:n,nonContractedUrl:s="https://qualiex.com/",educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:c,alias:d}){const[u,m]=i("qualiex"),h=e=>{t?.(e)},p=e=>{window.open(s,"_blank","noopener,noreferrer"),n?.(e)};return a("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[a(Fd,{value:u,onValueChange:m,className:"flex-1 flex flex-col min-h-0",children:[e(Ud,{className:"w-fit shrink-0",children:qd.map(e=>a(jd,{value:e.id,children:[e.label,a("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),qd.map(a=>e(Od,{value:a.id,className:"flex-1 mt-4 overflow-auto pr-2",children:e(Gd,{modules:a.modules,onModuleClick:h,contractedModules:"qualiex"===a.id?r:void 0,onModuleInterest:p})},a.id))]}),e(Vd,{educaUrl:o,saberGestaoUrl:l,wikiUrl:c,alias:d})]})}const Kd={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},Qd=6e5;function Xd(e){const{moduleAlias:a}=Id(),{alias:t,user:r,isAuthenticated:n}=zl(),i=e??a,l=r?.id??null,c=n&&!!t&&!!l,{data:d=[],isLoading:u}=lt({queryKey:["qualiex-associations",l,t],queryFn:()=>bl.fetchUserAssociations(l,t),enabled:c,staleTime:Qd,gcTime:12e5}),m=s(()=>t&&0!==d.length?d.find(e=>e.companyAlias===t)??null:null,[d,t]),h=o(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Kd[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:s(()=>!i||h(i),[i,h]),isLoading:c&&u,role:s(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:h}}function Jd(e){const{association:a}=Xd();return s(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=qd.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Kd[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Zd({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:c}){const{alias:d}=zl(),u=Jd(i);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{size:"lg",className:"overflow-hidden flex flex-col",children:[e(Es,{className:"sr-only",children:e(Ms,{children:"Módulos"})}),e(Yd,{onModuleClick:e=>{n?n(e):e.url&&Gi(Yi(e.url,d||void 0))},contractedModules:u,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:c,alias:d||void 0})]})})}function eu({open:t,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,userName:l,unitName:c,units:d=[],currentAlias:u,onUnitChange:m,onLogout:h,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,blocking:v=!0,size:x="lg",children:b}){const y=s(()=>{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(Cs,{open:t,onOpenChange:v?void 0:r,children:a(Ps,{size:x,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(Ms,{children:"Parece que você não tem acesso a essa página"}),e(Rs,{children:"Selecione um módulo para continuar navegando!"})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[y.length>1&&a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[e(aa,{className:"h-4 w-4 shrink-0"}),e("span",{className:"truncate text-xs",children:c||"Unidade"}),e(A,{className:"h-3 w-3 shrink-0"})]})}),e(xo,{align:"end",className:"max-h-[300px] overflow-auto",children:y.map(t=>a(bo,{onClick:()=>m?.(t),className:t.alias===u?"bg-muted":"",children:[e(aa,{className:"mr-2 h-4 w-4 shrink-0"}),e("span",{className:"truncate",children:t.name}),t.alias===u&&e(no,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},t.alias))})]}),a(co,{children:[e(uo,{asChild:!0,children:a(es,{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(qe,{className:"h-3.5 w-3.5 text-primary-foreground"})}),e(A,{className:"h-3 w-3"})]})}),a(xo,{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(Co,{}),a(bo,{onClick:h,children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),b?a("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[e("div",{className:"flex-1",children:b}),e(Vd,{educaUrl:p,saberGestaoUrl:f,wikiUrl:g,alias:u})]}):e(Yd,{onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:p,saberGestaoUrl:f,wikiUrl:g,alias:u})]})})}function au(e,a){return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function tu({children:a,contractedModules:r,onModuleClick:n,onModuleInterest:i,educaUrl:l="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:c="https://sabergestao.com.br/",wikiUrl:d,bypassPaths:u,accessDeniedRoutes:m}){const{hasAccess:h,isLoading:p,association:f}=Xd(),{user:g,alias:v,companies:x,isAuthenticated:b,isLoading:y,logout:N,switchUnit:w}=zl(),C=Jd(r),k=s(()=>x?.length?v&&x.find(e=>e.alias===v)||x[0]:null,[x,v]),_=s(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),S=o(e=>{const a=x?.find(a=>a.alias===e.alias);if(!a)return;const{pathname:t,search:r,hash:n}=window.location;if(v){const e=t.split("/"),i=e.indexOf(v);if(i>=0)return e[i]=a.alias,void(window.location.href=e.join("/")+r+n)}w(a)},[v,w,x]),A=o(e=>{n?n(e):e.url&&Gi(Yi(e.url,v||void 0))},[n,v]),D=s(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>au(e,[a]));return a?m[a]:void 0},[m]);return y||!b||u?.length&&au(window.location.pathname,u)?e(t,{children:a}):p?e("div",{className:"flex items-center justify-center min-h-screen",children:e(so,{size:"lg"})}):h?e(t,{children:a}):e(eu,{open:!0,onModuleClick:A,contractedModules:C,onModuleInterest:i,userName:g?.name,unitName:k?.name,units:_,currentAlias:v||void 0,onUnitChange:S,onLogout:N,educaUrl:l,saberGestaoUrl:c,wikiUrl:d,blocking:!0,children:D})}function ru({title:t,description:r,image:n,icon:i,ctaLabel:s="Quero conhecer mais",onCtaClick:o,children:l}){return a("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||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}):o?a(es,{onClick:o,size:"lg",className:"gap-2",children:[e(se,{className:"h-4 w-4"}),s]}):null]})}function nu({children:a,queryClient:t,moduleAlias:r,moduleAccessGuardProps:i,appTranslations:s}){const[o]=n.useState(()=>new dt({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),l=t??o;return n.useEffect(()=>{if(s)for(const[e,a]of Object.entries(s))kd(e,a)},[s]),e(zd,{children:e(nt,{i18n:wt,children:e(ut,{client:l,children:e(Ll,{children:e(Dd,{children:e(Td,{moduleAlias:r,children:e(tu,{...i,children:a})})})})})})})}const iu=_t.Root,su=r.forwardRef(({className:a,...t},r)=>e(_t.Item,{ref:r,className:Ki("border-b",a),...t}));su.displayName="AccordionItem";const ou=r.forwardRef(({className:t,children:r,...n},i)=>e(_t.Header,{className:"flex",children:a(_t.Trigger,{ref:i,className:Ki("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(A,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ou.displayName=_t.Trigger.displayName;const lu=r.forwardRef(({className:a,children:t,...r},n)=>e(_t.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:Ki("pb-4 pt-0",a),children:t})}));lu.displayName=_t.Content.displayName;const cu=r.forwardRef(({className:a,...t},r)=>e(St.Root,{ref:r,className:Ki("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));cu.displayName=St.Root.displayName;const du=r.forwardRef(({className:a,...t},r)=>e(St.Image,{ref:r,className:Ki("aspect-square h-full w-full",a),...t}));du.displayName=St.Image.displayName;const uu=r.forwardRef(({className:a,...t},r)=>e(St.Fallback,{ref:r,className:Ki("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));uu.displayName=St.Fallback.displayName;const mu=r.forwardRef(({...a},t)=>e("nav",{ref:t,"aria-label":"breadcrumb",...a}));mu.displayName="Breadcrumb";const hu=r.forwardRef(({className:a,...t},r)=>e("ol",{ref:r,className:Ki("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));hu.displayName="BreadcrumbList";const pu=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Ki("inline-flex items-center gap-1.5",a),...t}));pu.displayName="BreadcrumbItem";const fu=r.forwardRef(({asChild:a,className:t,...r},n)=>e(a?f:"a",{ref:n,className:Ki("transition-colors hover:text-foreground",t),...r}));fu.displayName="BreadcrumbLink";const gu=r.forwardRef(({className:a,...t},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Ki("font-normal text-foreground",a),...t}));gu.displayName="BreadcrumbPage";const vu=({children:a,className:t,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Ki("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:a??e(z,{})});vu.displayName="BreadcrumbSeparator";const xu=({className:t,...r})=>a("span",{role:"presentation","aria-hidden":"true",className:Ki("flex h-9 w-9 items-center justify-center",t),...r,children:[e(ra,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});xu.displayName="BreadcrumbEllipsis";const bu=g("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"}}),yu=r.forwardRef(({className:a,orientation:t,...r},n)=>e("div",{ref:n,className:Ki(bu({orientation:t}),a),...r}));function Nu({className:a,classNames:t,showOutsideDays:r=!0,...n}){return e(At,{showOutsideDays:r,className:Ki("p-3 pointer-events-auto",a),locale:Si,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:Ki(Zi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Ki(Zi({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:Ki(Zi({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?Ee:z,{className:"h-4 w-4"})},...n})}yu.displayName="ButtonGroup",Nu.displayName="Calendar";const wu={Root:function({children:a,className:t}){return e("div",{className:Ki("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:r}){return e(is,{className:Ki("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:e(cs,{className:"p-4",children:a})})},Field:function({label:t,value:r,className:n}){return a("div",{className:Ki("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 Cu({date:t,onDateChange:r,placeholder:n="Selecione uma data",disabled:i=!1,className:s,disabledDates:o}){return a(Eo,{children:[e(To,{asChild:!0,children:a(es,{variant:"outline",disabled:i,className:Ki("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",s),children:[e(Oe,{className:"mr-2 h-4 w-4"}),t?w(t,"d 'de' MMMM 'de' yyyy",{locale:Si}):e("span",{children:n})]})}),e(Io,{className:"w-auto p-0",align:"start",children:e(Nu,{mode:"single",selected:t,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const ku=({shouldScaleBackground:a=!0,...t})=>e(Dt.Root,{shouldScaleBackground:a,...t});ku.displayName="Drawer";const _u=Dt.Trigger,Su=Dt.Portal,Au=Dt.Close,Du=r.forwardRef(({className:a,...t},r)=>e(Dt.Overlay,{ref:r,className:Ki("fixed inset-0 z-50 bg-black/80",a),...t}));Du.displayName=Dt.Overlay.displayName;const Pu=r.forwardRef(({className:t,children:r,...n},i)=>a(Su,{children:[e(Du,{}),a(Dt.Content,{ref:i,className:Ki("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]})]}));Pu.displayName="DrawerContent";const Eu=({className:a,...t})=>e("div",{className:Ki("grid gap-1.5 p-4 text-center sm:text-left",a),...t});Eu.displayName="DrawerHeader";const Tu=({className:a,...t})=>e("div",{className:Ki("mt-auto flex flex-col gap-2 p-4",a),...t});Tu.displayName="DrawerFooter";const Iu=r.forwardRef(({className:a,...t},r)=>e(Dt.Title,{ref:r,className:Ki("text-lg font-semibold leading-none tracking-tight",a),...t}));Iu.displayName=Dt.Title.displayName;const Mu=r.forwardRef(({className:a,...t},r)=>e(Dt.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Mu.displayName=Dt.Description.displayName;const Ru={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))]"},Lu={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function zu({children:a,cols:t="auto-fit",gap:r="md",className:n}){return e("div",{className:Ki("grid",Ru[t],Lu[r],n),children:a})}const Fu=Pt.Root,Uu=Pt.Trigger,ju=r.forwardRef(({className:a,align:t="center",sideOffset:r=4,...n},i)=>e(Pt.Content,{ref:i,align:t,sideOffset:r,className:Ki("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}));ju.displayName=Pt.Content.displayName;const Ou=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-slot":"input-group",className:Ki("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}));Ou.displayName="InputGroup";const Bu=g("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"}}),$u=r.forwardRef(({className:a,align:t,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:Ki(Bu({align:t}),a),...r}));$u.displayName="InputGroupAddon";const Vu=g("",{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"}}),qu=r.forwardRef(({className:a,size:t,variant:r="ghost",...n},i)=>e(es,{ref:i,"data-slot":"input-group-button",variant:r,className:Ki(Vu({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",a),...n}));qu.displayName="InputGroupButton";const Wu=r.forwardRef(({className:a,...t},r)=>e(ts,{ref:r,"data-slot":"input-group-control",className:Ki("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Wu.displayName="InputGroupInput";const Hu=r.forwardRef(({className:a,...t},r)=>e(to,{ref:r,"data-slot":"input-group-control",className:Ki("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",a),...t}));Hu.displayName="InputGroupTextarea";const Gu=r.forwardRef(({className:a,...t},r)=>e("h1",{ref:r,className:Ki("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",a),...t}));Gu.displayName="H1";const Yu=r.forwardRef(({className:a,...t},r)=>e("h2",{ref:r,className:Ki("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",a),...t}));Yu.displayName="H2";const Ku=r.forwardRef(({className:a,...t},r)=>e("h3",{ref:r,className:Ki("scroll-m-20 text-2xl font-semibold tracking-tight",a),...t}));Ku.displayName="H3";const Qu=r.forwardRef(({className:a,...t},r)=>e("h4",{ref:r,className:Ki("scroll-m-20 text-xl font-semibold tracking-tight",a),...t}));Qu.displayName="H4";const Xu=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("leading-7 [&:not(:first-child)]:mt-6",a),...t}));Xu.displayName="P";const Ju=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-xl text-muted-foreground",a),...t}));Ju.displayName="Lead";const Zu=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,className:Ki("text-lg font-semibold",a),...t}));Zu.displayName="Large";const em=r.forwardRef(({className:a,...t},r)=>e("small",{ref:r,className:Ki("text-sm font-medium leading-none",a),...t}));em.displayName="Small";const am=r.forwardRef(({className:a,...t},r)=>e("p",{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));am.displayName="Muted";const tm=r.forwardRef(({className:a,...t},r)=>e("code",{ref:r,className:Ki("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",a),...t}));tm.displayName="InlineCode";const rm=r.forwardRef(({className:a,...t},r)=>e("blockquote",{ref:r,className:Ki("mt-6 border-l-2 pl-6 italic",a),...t}));rm.displayName="Blockquote";const nm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Ki("my-6 ml-6 list-disc [&>li]:mt-2",a),...t}));nm.displayName="List";const im=r.forwardRef(({className:t,children:r,...n},i)=>a(Et.Root,{ref:i,className:Ki("relative z-10 flex max-w-max flex-1 items-center justify-center",t),...n,children:[r,e(mm,{})]}));im.displayName=Et.Root.displayName;const sm=r.forwardRef(({className:a,...t},r)=>e(Et.List,{ref:r,className:Ki("group flex flex-1 list-none items-center justify-center space-x-1",a),...t}));sm.displayName=Et.List.displayName;const om=Et.Item,lm=g("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"),cm=r.forwardRef(({className:t,children:r,...n},i)=>a(Et.Trigger,{ref:i,className:Ki(lm(),"group",t),...n,children:[r," ",e(A,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));cm.displayName=Et.Trigger.displayName;const dm=r.forwardRef(({className:a,...t},r)=>e(Et.Content,{ref:r,className:Ki("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}));dm.displayName=Et.Content.displayName;const um=Et.Link,mm=r.forwardRef(({className:a,...t},r)=>e("div",{className:Ki("absolute left-0 top-full flex justify-center"),children:e(Et.Viewport,{className:Ki("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})}));mm.displayName=Et.Viewport.displayName;const hm=r.forwardRef(({className:a,...t},r)=>e(Et.Indicator,{ref:r,className:Ki("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 pm({items:r,maxItems:n=3,className:i}){const s=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(mu,{className:i,children:e(hu,{children:s.map((r,n)=>{const i=o&&1===n;return a(pu,{children:[!(0===n)&&e(vu,{}),i&&a(t,{children:[e(xu,{}),e(vu,{})]}),r.isCurrentPage?e(gu,{children:r.label}):e(fu,{asChild:!0,children:e(vt,{to:r.href||"/",children:r.label})})]},r.label)})})})}function fm(){const e=ft();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,s=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:s,href:i?void 0:r,isCurrentPage:i})}),t})()}hm.displayName=Et.Indicator.displayName;const gm=({className:a,...t})=>e("nav",{role:"navigation","aria-label":"pagination",className:Ki("mx-auto flex w-full justify-center",a),...t});gm.displayName="Pagination";const vm=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,className:Ki("flex flex-row items-center gap-1",a),...t}));vm.displayName="PaginationContent";const xm=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,className:Ki("",a),...t}));xm.displayName="PaginationItem";const bm=({className:a,isActive:t,size:r="icon",...n})=>e("a",{"aria-current":t?"page":void 0,className:Ki(Zi({variant:t?"outline":"ghost",size:r}),a),...n});bm.displayName="PaginationLink";const ym=({className:t,...r})=>a(bm,{"aria-label":"Go to previous page",size:"default",className:Ki("gap-1 pl-2.5",t),...r,children:[e(Ee,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});ym.displayName="PaginationPrevious";const Nm=({className:t,...r})=>a(bm,{"aria-label":"Go to next page",size:"default",className:Ki("gap-1 pr-2.5",t),...r,children:[e("span",{children:"Next"}),e(z,{className:"h-4 w-4"})]});Nm.displayName="PaginationNext";const wm=({className:t,...r})=>a("span",{"aria-hidden":!0,className:Ki("flex h-9 w-9 items-center justify-center",t),...r,children:[e(ra,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});wm.displayName="PaginationEllipsis";const Cm=r.forwardRef(({className:a,value:t,...r},n)=>e(Tt.Root,{ref:n,className:Ki("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...r,children:e(Tt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Cm.displayName=Tt.Root.displayName;const km=r.forwardRef(({className:a,...t},r)=>e(It.Root,{className:Ki("grid gap-2",a),...t,ref:r}));km.displayName=It.Root.displayName;const _m=r.forwardRef(({className:a,...t},r)=>e(It.Item,{ref:r,className:Ki("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(It.Indicator,{className:"flex items-center justify-center",children:e(F,{className:"h-2.5 w-2.5 fill-current text-current"})})}));_m.displayName=It.Item.displayName;const Sm=({className:a,...t})=>e(Mt.PanelGroup,{className:Ki("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",a),...t}),Am=Mt.Panel,Dm=({withHandle:a,className:t,...r})=>e(Mt.PanelResizeHandle,{className:Ki("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:a&&e("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:e(Z,{className:"h-2.5 w-2.5"})})}),Pm=Va.Root,Em=Va.Trigger,Tm=Va.Close,Im=Va.Portal,Mm=r.forwardRef(({className:a,...t},r)=>e(Va.Overlay,{className:Ki("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}));Mm.displayName=Va.Overlay.displayName;const Rm=g("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"}}),Lm=r.forwardRef(({side:t="right",className:r,children:n,...i},s)=>a(Im,{children:[e(Mm,{}),a(Va.Content,{ref:s,className:Ki(Rm({side:t}),r),...i,children:[n,a(Va.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Lm.displayName=Va.Content.displayName;const zm=({className:t,showSeparator:r=!1,children:n,...i})=>a("div",{className:Ki("flex flex-col flex-shrink-0",t),...i,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(us,{className:"mt-2"})]});zm.displayName="SheetHeader";const Fm=({className:a,...t})=>e("div",{className:Ki("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",a),...t});Fm.displayName="SheetBody";const Um=({className:t,children:r,...n})=>a("div",{className:"flex-shrink-0 pt-4",children:[e(us,{className:"mb-4"}),e("div",{className:Ki("flex flex-row justify-end gap-2",t),...n,children:r})]});Um.displayName="SheetFooter";const jm=r.forwardRef(({className:a,...t},r)=>e(Va.Title,{ref:r,className:Ki("text-lg font-semibold text-foreground",a),...t}));jm.displayName=Va.Title.displayName;const Om=r.forwardRef(({className:a,...t},r)=>e(Va.Description,{ref:r,className:Ki("text-sm text-muted-foreground",a),...t}));Om.displayName=Va.Description.displayName;const Bm="sidebar:state",$m=r.createContext(null);function Vm(){const e=r.useContext($m);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const qm=r.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:n,className:i,style:s,children:o,...l},c)=>{const d=Ol(),[u,m]=r.useState(!1),[h,p]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Bm);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(Bm,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 x=f?"expanded":"collapsed",b=r.useMemo(()=>({state:x,open:f,setOpen:g,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[x,f,g,d,u,m,v]);return e($m.Provider,{value:b,children:e(_o,{delayDuration:0,children:e("div",{className:Ki("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",...s},ref:c,...l,children:o})})})});qm.displayName="SidebarProvider";const Wm=r.forwardRef(({side:t="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:s,...o},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=Vm();return"none"===n?e("div",{className:Ki("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...o,children:s}):c?e(Pm,{open:u,onOpenChange:m,...o,children:a(Lm,{"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(jm,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:s})]})}):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:Ki("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:Ki("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),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:s})})]})});Wm.displayName="Sidebar";const Hm=r.forwardRef(({className:t,onClick:r,...n},i)=>{const{toggleSidebar:s}=Vm();return a(es,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Ki("h-7 w-7",t),onClick:e=>{r?.(e),s()},...n,children:[e(na,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Hm.displayName="SidebarTrigger";const Gm=r.forwardRef(({className:a,...t},r)=>{const{toggleSidebar:n}=Vm();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Ki("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})});Gm.displayName="SidebarRail";const Ym=r.forwardRef(({className:a,...t},r)=>e("main",{ref:r,className:Ki("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}));Ym.displayName="SidebarInset";const Km=r.forwardRef(({className:a,...t},r)=>e(ts,{ref:r,"data-sidebar":"input",className:Ki("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));Km.displayName="SidebarInput";const Qm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"header",className:Ki("flex flex-col gap-2 p-2",a),...t}));Qm.displayName="SidebarHeader";const Xm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Ki("flex flex-col gap-2 p-2",a),...t}));Xm.displayName="SidebarFooter";const Jm=r.forwardRef(({className:a,...t},r)=>e(us,{ref:r,"data-sidebar":"separator",className:Ki("mx-2 w-auto bg-sidebar-border",a),...t}));Jm.displayName="SidebarSeparator";const Zm=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"content",className:Ki("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));Zm.displayName="SidebarContent";const eh=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group",className:Ki("relative flex w-full min-w-0 flex-col p-2",a),...t}));eh.displayName="SidebarGroup";const ah=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?f:"div",{ref:n,"data-sidebar":"group-label",className:Ki("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}));ah.displayName="SidebarGroupLabel";const th=r.forwardRef(({className:a,asChild:t=!1,...r},n)=>e(t?f:"button",{ref:n,"data-sidebar":"group-action",className:Ki("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}));th.displayName="SidebarGroupAction";const rh=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Ki("w-full text-sm",a),...t}));rh.displayName="SidebarGroupContent";const nh=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Ki("flex w-full min-w-0 flex-col gap-1",a),...t}));nh.displayName="SidebarMenu";const ih=r.forwardRef(({className:a,...t},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Ki("group/menu-item relative",a),...t}));ih.displayName="SidebarMenuItem";const sh=g("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"}}),oh=r.forwardRef(({asChild:t=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:s,className:o,...l},c)=>{const d=t?f:"button",{isMobile:u,state:m}=Vm(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Ki(sh({variant:n,size:i}),o),...l});return s?("string"==typeof s&&(s={children:s}),a(So,{children:[e(Ao,{asChild:!0,children:h}),e(Do,{side:"right",align:"center",hidden:"collapsed"!==m||u,...s})]})):h});oh.displayName="SidebarMenuButton";const lh=r.forwardRef(({className:a,asChild:t=!1,showOnHover:r=!1,...n},i)=>e(t?f:"button",{ref:i,"data-sidebar":"menu-action",className:Ki("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}));lh.displayName="SidebarMenuAction";const ch=r.forwardRef(({className:a,...t},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Ki("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}));ch.displayName="SidebarMenuBadge";const dh=r.forwardRef(({className:t,showIcon:n=!1,...i},s)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return a("div",{ref:s,"data-sidebar":"menu-skeleton",className:Ki("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":o}})]})});dh.displayName="SidebarMenuSkeleton";const uh=r.forwardRef(({className:a,...t},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Ki("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}));uh.displayName="SidebarMenuSub";const mh=r.forwardRef(({...a},t)=>e("li",{ref:t,...a}));mh.displayName="SidebarMenuSubItem";const hh=r.forwardRef(({asChild:a=!1,size:t="md",isActive:r,className:n,...i},s)=>e(a?f:"a",{ref:s,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Ki("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}));hh.displayName="SidebarMenuSubButton";const ph=r.forwardRef(({className:t,value:r,defaultValue:n,...i},s)=>{const o=r||n||[0];return a(Rt.Root,{ref:s,value:r,defaultValue:n,className:Ki("relative flex w-full touch-none select-none items-center",t),...i,children:[e(Rt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Rt.Range,{className:"absolute h-full bg-primary"})}),o.map((a,t)=>e(Rt.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 fh({children:a,className:t}){return e("div",{className:Ki("flex flex-col h-full",t),children:e(Ho,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:a})})})}function gh({title:t,description:r,actions:n,className:i}){return a("div",{className:Ki("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(us,{})]})}function vh({children:a,className:t}){return e("div",{className:Ki("space-y-6",t),children:a})}ph.displayName=Rt.Root.displayName;const xh=Lt.Menu,bh=Lt.Group,yh=Lt.Portal,Nh=Lt.Sub,wh=Lt.RadioGroup,Ch=r.forwardRef(({className:a,...t},r)=>e(Lt.Root,{ref:r,className:Ki("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",a),...t}));Ch.displayName=Lt.Root.displayName;const kh=r.forwardRef(({className:a,...t},r)=>e(Lt.Trigger,{ref:r,className:Ki("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}));kh.displayName=Lt.Trigger.displayName;const _h=r.forwardRef(({className:t,inset:r,children:n,...i},s)=>a(Lt.SubTrigger,{ref:s,className:Ki("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(z,{className:"ml-auto h-4 w-4"})]}));_h.displayName=Lt.SubTrigger.displayName;const Sh=r.forwardRef(({className:a,...t},r)=>e(Lt.SubContent,{ref:r,className:Ki("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}));Sh.displayName=Lt.SubContent.displayName;const Ah=r.forwardRef(({className:a,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},s)=>e(Lt.Portal,{children:e(Lt.Content,{ref:s,align:t,alignOffset:r,sideOffset:n,className:Ki("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})}));Ah.displayName=Lt.Content.displayName;const Dh=r.forwardRef(({className:a,inset:t,...r},n)=>e(Lt.Item,{ref:n,className:Ki("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}));Dh.displayName=Lt.Item.displayName;const Ph=r.forwardRef(({className:t,children:r,checked:n,...i},s)=>a(Lt.CheckboxItem,{ref:s,className:Ki("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(Lt.ItemIndicator,{children:e(P,{className:"h-4 w-4"})})}),r]}));Ph.displayName=Lt.CheckboxItem.displayName;const Eh=r.forwardRef(({className:t,children:r,...n},i)=>a(Lt.RadioItem,{ref:i,className:Ki("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(Lt.ItemIndicator,{children:e(F,{className:"h-2 w-2 fill-current"})})}),r]}));Eh.displayName=Lt.RadioItem.displayName;const Th=r.forwardRef(({className:a,inset:t,...r},n)=>e(Lt.Label,{ref:n,className:Ki("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...r}));Th.displayName=Lt.Label.displayName;const Ih=r.forwardRef(({className:a,...t},r)=>e(Lt.Separator,{ref:r,className:Ki("-mx-1 my-1 h-px bg-muted",a),...t}));Ih.displayName=Lt.Separator.displayName;const Mh=({className:a,...t})=>e("span",{className:Ki("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});Mh.displayname="MenubarShortcut";const Rh={light:"",dark:".dark"},Lh=r.createContext(null);function zh(){const e=r.useContext(Lh);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Fh=r.forwardRef(({id:t,className:n,children:i,config:s,...o},l)=>{const c=r.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return e(Lh.Provider,{value:{config:s},children:a("div",{"data-chart":d,ref:l,className:Ki("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Uh,{id:d,config:s}),e(zt.ResponsiveContainer,{children:i})]})})});Fh.displayName="Chart";const Uh=({id:a,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Rh).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},jh=zt.Tooltip,Oh=r.forwardRef(({active:n,payload:i,className:s,indicator:o="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:x}=zh(),b=r.useMemo(()=>{if(l||!i?.length)return null;const[a]=i,t=Vh(x,a,`${g||a?.dataKey||a?.name||"value"}`),r=g||"string"!=typeof d?t?.label:x[d]?.label||d;return u?e("div",{className:Ki("font-medium",m),children:u(r,i)}):r?e("div",{className:Ki("font-medium",m),children:r}):null},[d,u,i,l,m,x,g]);if(!n||!i?.length)return null;const y=1===i.length&&"dot"!==o;return a("div",{ref:v,className:Ki("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",s),children:[y?null:b,e("div",{className:"grid gap-1.5",children:i.map((r,n)=>{const i=`${f||r.name||r.dataKey||"value"}`,s=Vh(x,r,i),l=p||r.payload?.fill||r.color;return e("div",{className:Ki("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):a(t,{children:[s?.icon?e(s.icon,{}):!c&&e("div",{className:Ki("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":y&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),a("div",{className:Ki("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[a("div",{className:"grid gap-1.5",children:[y?b:null,e("span",{className:"text-muted-foreground",children:s?.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)})})]})});Oh.displayName="ChartTooltip";const Bh=zt.Legend,$h=r.forwardRef(({className:t,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:s},o)=>{const{config:l}=zh();return n?.length?e("div",{ref:o,className:Ki("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",t),children:n.map(t=>{const n=`${s||t.dataKey||"value"}`,i=Vh(l,t,n);return a("div",{className:Ki("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 Vh(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]}$h.displayName="ChartLegend";const qh=({onClick:a,isActive:t,disabled:r,children:n,title:i})=>e("button",{type:"button",onClick:a,disabled:r,title:i,className:Ki("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}),Wh=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),Hh=({value:t,onChange:n,disabled:s,placeholder:l="Escreva o conteúdo aqui...",minHeight:c="300px",showModeToggle:d=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=i("visual"),f=Zt({extensions:[ar.configure({heading:{levels:[1,2,3]}}),tr,rr.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),nr,ir,sr.configure({multicolor:!0})],content:t||"",editable:!s,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&t!==f.getHTML()&&f.commands.setContent(t||"")},[t,f]);const g=o(()=>{if(!f)return;const e=f.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?f.chain().focus().extendMarkRange("link").setLink({href:a}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?a("div",{className:Ki("space-y-2",m),children:[d&&a("div",{className:"flex justify-between items-center",children:[a("div",{className:"flex gap-1",children:[a(es,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:s,children:[e(ia,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),a(es,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:s,children:[e(sa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),a(es,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:s,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(qh,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:s,title:"Título 1",children:e(oa,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:s,title:"Título 2",children:e(la,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:s,title:"Título 3",children:e(ca,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:s,title:"Negrito",children:e(da,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:s,title:"Itálico",children:e(ua,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:s,title:"Sublinhado",children:e(ma,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:s,title:"Riscado",children:e(ha,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:s,title:"Lista",children:e(Q,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:s,title:"Lista Ordenada",children:e(pa,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:s,title:"Destacar",children:e(fa,{className:"h-4 w-4"})}),e(qh,{onClick:g,isActive:f.isActive("link"),disabled:s,title:"Link",children:e(ga,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:s,title:"Limpar Formatação",children:e(va,{className:"h-4 w-4"})}),e(Wh,{}),e(qh,{onClick:()=>f.chain().focus().undo().run(),disabled:s||!f.can().undo(),title:"Desfazer",children:e(xa,{className:"h-4 w-4"})}),e(qh,{onClick:()=>f.chain().focus().redo().run(),disabled:s||!f.can().redo(),title:"Refazer",children:e(ba,{className:"h-4 w-4"})})]}),e(er,{editor:f,className:Ki("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:s,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 Gh({image:a,title:t,className:r}){return e("div",{className:Ki("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(ya,{className:"w-16 h-16 text-muted-foreground"})})})}function Yh({steps:t,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:s}){const o=t.length,l=(r+1)/o*100;return a("div",{className:Ki("flex items-center gap-3",s),children:[a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",o,e(A,{className:"h-3 w-3 ml-1"})]})}),e(xo,{align:"start",children:t.map((e,t)=>a(bo,{onClick:()=>n(t),className:Ki(t===r&&"bg-accent"),children:[t+1,". ",e.title]},e.id))})]}),e(Cm,{value:l,className:"w-32 h-2"})]})}function Kh({currentStepIndex:t,totalSteps:r,onBack:n,onNext:i,onComplete:s,backButtonText:o,continueButtonText:l,finishButtonText:c,className:d}){const u=0===t,m=t===r-1;return a("div",{className:Ki("flex items-center gap-2",d),children:[!u&&a(es,{variant:"outline",onClick:n,size:"sm",children:[e(Pe,{className:"h-4 w-4 mr-2"}),o]}),a(es,{onClick:m?s:i,size:"sm",children:[m?c:l,!m&&e(De,{className:"h-4 w-4 ml-2"})]})]})}const Qh=r.forwardRef(({open:t,onOpenChange:n,steps:i,onComplete:s,onStepChange:o,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[x,b]=r.useState(0),y=void 0!==p,N=y?p:x,w=r.useCallback(e=>{y?f?.(e):b(e),o?.(e)},[y,f,o]);r.useEffect(()=>{t||y||b(0)},[t,y]);const C=i[N],k=i.length;return C?e(Cs,{open:t,onOpenChange:n,children:a(Ps,{ref:v,size:m,variant:"informative",className:Ki("p-0 gap-0 overflow-hidden",g),children:[a(Ss,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),e("div",{className:"flex-1 min-h-0 overflow-auto",children:a("div",{className:"p-6 space-y-4",children:[e(Gh,{image:C.image,title:C.title}),e(Ms,{className:"text-xl font-semibold",children:C.title}),e(Rs,{className:"text-muted-foreground",children:C.description})]})}),a("div",{className:"flex-shrink-0",children:[e(us,{}),a("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?e(Yh,{steps:i,currentStepIndex:N,onStepSelect:e=>{w(e)},stepLabel:u}):e("div",{}),e(Kh,{currentStepIndex:N,totalSteps:k,onBack:()=>{N>0&&w(N-1)},onNext:()=>{N<k-1&&w(N+1)},onComplete:()=>{s?.(),n(!1)},backButtonText:c,continueButtonText:l,finishButtonText:d})]})]})]})}):null});function Xh({label:t,onClick:r,icon:n,actions:i=[],variant:s="default",size:o="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(i.length>0))return a(es,{variant:s,size:o,disabled:m,onClick:r,className:u,children:[c?e(E,{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:Ki("inline-flex rounded-md shadow-sm",u),children:[a(es,{variant:s,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(E,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,t]}),a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:s,size:o,disabled:m,className:Ki("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(A,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(xo,{align:d,className:"min-w-[160px]",children:i.map(t=>{const r=t.icon;return a(bo,{onClick:t.onClick,disabled:t.disabled,className:Ki("destructive"===t.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),t.label]},t.id)})})]})]})}var Jh,Zh;Qh.displayName="OnboardingDialog",(Zh=Jh||(Jh={})).CSV="csv",Zh.PDF="pdf",Zh.XLSX="xlsx",Zh.PNG="png",Zh.JPEG="jpeg",Zh.SVG="svg";const ep=[{value:Jh.CSV,label:"CSV",icon:e(xe,{className:"h-5 w-5"})},{value:Jh.PDF,label:"PDF",icon:e(xe,{className:"h-5 w-5"})},{value:Jh.XLSX,label:"XLSX",icon:e(Na,{className:"h-5 w-5"})}],ap=[{value:Jh.PNG,label:"PNG",icon:e(Fe,{className:"h-5 w-5"})},{value:Jh.JPEG,label:"JPEG",icon:e(wa,{className:"h-5 w-5"})},{value:Jh.SVG,label:"SVG",icon:e(wa,{className:"h-5 w-5"})},{value:Jh.PDF,label:"PDF",icon:e(xe,{className:"h-5 w-5"})}];function tp({open:t,onOpenChange:r,onExport:n,mode:s="table",options:o,title:l,description:c,cancelLabel:d="Cancelar",exportLabel:u="Exportar"}){const[m,h]=i(""),p=o??("chart"===s?ap:ep),f=c??"Selecione o formato do arquivo",g=e=>{e||h(""),r(e)};return e(Cs,{open:t,onOpenChange:g,children:a(Ps,{className:"sm:max-w-md",variant:"form",isDirty:!!m,children:[e(Es,{children:e(Ms,{children:l??("chart"===s?"Exportar gráfico":"Exportar tabela")})}),a("div",{className:"py-4",children:[e("p",{className:"text-sm text-muted-foreground mb-4",children:f}),e(km,{value:m,onValueChange:h,className:"gap-3",children:p.map(t=>a("div",{className:"flex items-center space-x-3",children:[e(_m,{value:t.value,id:`export-${t.value}`}),a(ns,{htmlFor:`export-${t.value}`,className:Ki("flex items-center gap-2 cursor-pointer font-normal",m===t.value&&"font-medium"),children:[t.icon,t.label]})]},t.value))})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>g(!1),children:d}),e(es,{onClick:()=>{m&&(n(m),r(!1),h(""))},disabled:!m,children:u})]})]})})}const rp=p(({value:t,onChange:n,onTimeChange:i,label:s,error:l,format:c="24h",className:d,id:u,...m},h)=>{const p=u??r.useId(),f=o(e=>{const a=e.target.value;n?.(a),i?.(a)},[n,i]),g=o(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return a("div",{className:Ki("grid gap-1.5",d),children:[s&&e(ns,{htmlFor:p,children:s}),a("div",{className:"relative",children:[e(ts,{ref:h,id:p,type:"time",value:t??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Ki("pr-9",l&&"border-destructive focus-visible:ring-destructive"),...m}),e(Ae,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),l&&e("p",{className:"text-sm text-destructive",children:l})]})});function np({open:t,onOpenChange:r,onConfirm:n,onGenerateCode:s,mode:l="code",email:c,maxLength:d=8,title:u="Assinatura Eletrônica",description:m,confirmLabel:h="Confirmar",cancelLabel:p="Cancelar",resendLabel:f="Reenviar código",errorMessage:g}){const v="password"===l,x=m??(v?"Digite sua senha para confirmar a operação.":"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação."),[b,y]=i(""),[N,w]=i(!1),[C,k]=i(!1),[_,S]=i(null),A=o(async()=>{if(b.trim()){w(!0),S(null);try{await n(b)?(y(""),r(!1)):S(g??(v?"Senha incorreta. Tente novamente.":"Código inválido. Tente novamente."))}catch{S(g??(v?"Erro ao validar a senha. Tente novamente.":"Erro ao validar o código. Tente novamente."))}finally{w(!1)}}},[b,n,r,g,v]),D=o(async()=>{if(s){k(!0),S(null);try{await s()}catch{S("Erro ao reenviar o código.")}finally{k(!1)}}},[s]),P=e=>{e||(y(""),S(null)),r(e)},E=v?"Senha":"Código de verificação",T=v?"Digite sua senha":"Digite o código";return e(Cs,{open:t,onOpenChange:P,children:a(Ps,{className:"sm:max-w-md",variant:"form",isDirty:!!b,children:[e(Es,{children:a(Ms,{className:"flex items-center gap-2",children:[e(v?pe:Ca,{className:"h-5 w-5 text-primary"}),u]})}),a("div",{className:"py-4 space-y-4",children:[e("p",{className:"text-sm text-muted-foreground",children:x}),!v&&c&&a("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[e($e,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-muted-foreground",children:"Enviado para:"}),e("span",{className:"font-medium",children:c})]}),a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"signature-input",children:E}),e(ts,{id:"signature-input",type:v?"password":"text",value:b,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"===e.key&&b.trim()&&(e.preventDefault(),A())},maxLength:v?void 0:d,placeholder:T,autoFocus:!0,className:Ki(_&&"border-destructive focus-visible:ring-destructive")}),_&&e("p",{className:"text-sm text-destructive",children:_})]}),!v&&a(es,{variant:"ghost",size:"sm",onClick:D,disabled:C,className:"text-primary",children:[e(Je,{className:Ki("h-4 w-4 mr-1",C&&"animate-spin")}),f]})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>P(!1),disabled:N,children:p}),e(es,{onClick:A,disabled:!b.trim()||N,children:N?"Validando...":h})]})]})})}function ip({currentStep:t,totalSteps:r,onStepChange:n,stepLabels:i,canGoToStep:s,className:o,progressWidth:l="w-32"}){const c=Array.from({length:r},(e,a)=>a+1),d=e=>!(e<=t)&&(!!s&&!s(e));return a("div",{className:Ki("flex items-center gap-3",o),children:[a(co,{children:[e(uo,{asChild:!0,children:a(es,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",t,"/",r,e(A,{className:"h-3 w-3 ml-1"})]})}),e(xo,{align:"start",children:c.map(r=>a(bo,{onClick:()=>{var e;(e=r)<t?n(e):s&&!s(e)||n(e)},disabled:d(r),className:Ki("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(P,{className:"h-4 w-4 ml-auto"})]},r))})]}),e(Cm,{value:t/r*100,className:Ki("h-2",l)})]})}function sp(e){const a=cl.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 op(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await xl.handleApiError({status:401})){const n={...a,headers:sp(t)};r=await fetch(e,n)}}return r}function lp(e){const[a,t]=i([]),[r,n]=i(0),[s,l]=i(!1);u(()=>{if(!e)return;let a=!1;const r=`${Pr().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){l(!0);try{const i=sp(e),s=await op(r,{method:"GET",headers:i},e);if(!s.ok)return;const o=await s.json();!a&&o.data?.[0]&&(t(o.data[0].updates??[]),n(o.data[0].valueBadge??0))}catch(i){}finally{a||l(!1)}}(),()=>{a=!0}},[e]);const c=o(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${Pr().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=sp(e),r=JSON.stringify({id:t,idUpdateType:3});await op(i,{method:"POST",headers:a,body:r},e)}catch(s){}},[e,r,a]);return{updates:a,badgeCount:r,loading:s,markAsVisualized:c}}rp.displayName="Timepicker";const cp=n.forwardRef(({updates:t,badgeCount:r,onOpen:n,onViewAll:i},s)=>{const o=void 0===t,l=zl(),c=l?.alias??null,d=lp(o?c:null),u=o?d.updates??[]:t,m=o?d.badgeCount??0:r??0,h=n??(o?d.markAsVisualized:void 0),p=i??(o&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return a(Eo,{children:[e(To,{asChild:!0,children:a(es,{ref:s,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(ka,{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(Io,{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(ka,{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(es,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:p,children:["Ver todas as atualizações",e(De,{className:"h-[18px] w-[18px]"})]})})]})]})});var dp,up,mp,hp;cp.displayName="UpdatesNotification",(up=dp||(dp={}))[up.none=0]="none",up[up.image=1]="image",up[up.video=2]="video",up[up.audio=3]="audio",up[up.wopi=4]="wopi",up[up.onlineEditor=5]="onlineEditor",up[up.report=6]="report",(hp=mp||(mp={}))[hp.SimplePrint=0]="SimplePrint",hp[hp.ManagedCopy=1]="ManagedCopy",hp[hp.NonManagedCopy=2]="NonManagedCopy";const pp={".jpg":dp.image,".jpeg":dp.image,".png":dp.image,".bmp":dp.image,".gif":dp.image,".svg":dp.image,".webp":dp.image,".wav":dp.audio,".mp3":dp.audio,".mp4":dp.video,".webm":dp.video,".ogg":dp.video,".pdf":dp.wopi,".ods":dp.wopi,".xls":dp.wopi,".xlsb":dp.wopi,".xlsm":dp.wopi,".xlsx":dp.wopi,".doc":dp.wopi,".docm":dp.wopi,".docx":dp.wopi,".dot":dp.wopi,".dotm":dp.wopi,".dotx":dp.wopi,".odt":dp.wopi,".odp":dp.wopi,".pot":dp.wopi,".potm":dp.wopi,".potx":dp.wopi,".pps":dp.wopi,".ppsm":dp.wopi,".ppsx":dp.wopi,".ppt":dp.wopi,".pptm":dp.wopi,".pptx":dp.wopi,".gdocs":dp.onlineEditor,".gsheets":dp.onlineEditor};function fp(e){return e?pp[e.toLowerCase()]??dp.none:dp.none}function gp(e){return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const vp={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function xp(e){return vp[e?.toLowerCase()]||""}function bp(e){const{viewerUrl:a,wopiUrl:t,fileId:r,token:n,extension:i,language:s="pt-br"}=e,o=xp(i);if(!o)return null;return`${a}${o}ui=${s}&rs=${s}&access_token=${n}&WOPISrc=${encodeURIComponent(`${t}${r}`)}`}function yp({open:r,onOpenChange:n,template:i,viewerType:s,isLoading:l=!1,enableDownload:c=!0,onDownload:m,isDownloading:h=!1,enableFavorite:p=!1,isFavorite:f=!1,onFavorite:g,isFavoriting:v=!1,enableConfirmReading:x=!1,readingConfirmationDate:b,onConfirmReading:y,isConfirmingReading:N=!1,readingConfirmationTimeRemaining:w,onIframeLoad:C,className:k}){const _=d(null),A=s??fp(i.extension),D=h||N||v,P=i.code?`${i.code} – ${i.name}`:i.name,E=o(()=>{_.current&&C&&C(_.current)},[C]);return u(()=>{if(!r)return;const e=e=>{"Escape"===e.key&&n(!1)};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[r,n]),e(Cs,{open:r,onOpenChange:n,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(A===dp.wopi||A===dp.report)&&"w-[90vw]",k),children:[a("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[e("h2",l?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:P}),a("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!l&&a(t,{children:[(x||b)&&e(t,{children:b?a("div",{className:"flex flex-col mr-2.5",children:[a("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[e(_a,{className:"h-4 w-4"}),"Leitura confirmada"]}),e("span",{className:"text-xs text-muted-foreground ml-5",children:b.toLocaleDateString()})]}):null!=w&&w>0?a("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[e("span",{children:"Confirmação disponível em"}),e("span",{className:"font-medium min-w-[72px]",children:Np(w)}),e("span",{children:"segundos"})]}):a(es,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[e(Ca,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":"Confirmar leitura"]})}),A!==dp.none&&p&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:e(Ge,{className:Ki("h-4 w-4",f&&"fill-accent text-accent")})})}),e(Do,{children:f?"Desfavoritar":"Favoritar"})]}),A!==dp.none&&c&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>m?.(),children:e(Ce,{className:"h-4 w-4"})})}),e(Do,{children:"Download"})]})]}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})]})]}),e("div",{className:Ki("flex flex-col items-center justify-center min-h-[160px] w-full",l&&"relative -top-5",A===dp.none&&"min-h-[124px]",A===dp.image&&"max-h-[85vh]",(A===dp.wopi||A===dp.report)&&"min-w-[77vw] min-h-[80vh]"),children:l?e(so,{className:"h-14 w-14"}):a(t,{children:[(A===dp.none||!i.url)&&a("div",{className:"text-center",children:[e("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),e("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),A===dp.image&&e("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),A===dp.video&&e("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),A===dp.audio&&e("audio",{controls:!0,autoPlay:!0,src:i.url}),(A===dp.wopi||A===dp.report)&&a("div",{className:"relative w-full h-[79.5vh]",children:[e(so,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e("iframe",{ref:_,src:i.url,onLoad:E,className:"border-none w-full h-full z-[1] relative",title:i.name})]})]})}),!l&&A===dp.none&&a("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[e(es,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),c&&e(es,{variant:"default",onClick:()=>m?.(),children:"Download"})]})]})})}function Np(e){const a=e%60;return`${Math.floor(e/60)}min ${a<10?"0":""}${a}`}function wp({open:t,onOpenChange:r,identifier:n,fileName:s,mode:l="edit",type:c="document",onClose:d,className:m}){const[h,p]=i(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,l,c);u(()=>{if(t){p(!0);const e=setTimeout(()=>p(!1),300);return()=>clearTimeout(e)}},[t]);const g=o(()=>{d?.(),r(!1)},[d,r]);return u(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&g()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[t,g]),e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",m),children:[a("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[e("h2",h?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:s}),e("div",{className:"flex items-center ml-4 z-20",children:a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})})]}),e("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:h?e(so,{className:"h-14 w-14"}):a("div",{className:"relative w-full h-[79.5vh]",children:[e(so,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),e("iframe",{src:f,className:"border-none w-full h-full z-[1] relative",title:s})]})})]})})}function Cp({open:t,onOpenChange:r,url:n,title:i,className:s,minHeight:l="250px"}){const c=o(()=>{r(!1)},[r]);return u(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&c()};return window.addEventListener("keyup",e),()=>window.removeEventListener("keyup",e)},[t,c]),e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:Ki("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",s),children:[a("div",{className:"flex items-center justify-end mb-2.5",children:[i&&e("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:i}),a(So,{children:[e(Ao,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:e(S,{className:"h-4 w-4"})})}),e(Do,{children:"Fechar"})]})]}),e("iframe",{src:n,className:"border-none w-full",style:{minHeight:l},title:i||"Embedded content"})]})})}function kp({term:r,open:n,onClose:s,onAgree:l,title:c="Termos de Uso Atualizados",seeLaterLabel:d="Ver depois",agreeLabel:u="Li e concordo",viewTermLabel:m="Visualizar termo de uso"}){const[h,p]=i(!1),f=o(()=>{l(r.id)},[l,r.id]);return a(t,{children:[e(Cs,{open:n&&!h,onOpenChange:e=>!e&&s(),children:a(Ps,{className:"sm:max-w-md",children:[e(Es,{children:a(Ms,{className:"flex items-center gap-2",children:[e(Ca,{className:"h-5 w-5 text-primary"}),c]})}),a("div",{className:"space-y-4",children:[r.description&&e(Ho,{className:"max-h-48",children:e("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:r.description}})}),r.file&&a(es,{variant:"link",className:"px-0 text-primary",onClick:()=>p(!0),children:[e(Ze,{className:"mr-1 h-4 w-4"}),m]})]}),a(Is,{className:"gap-2 sm:gap-0",children:[e(es,{variant:"ghost",onClick:s,children:d}),e(es,{onClick:f,children:u})]})]})}),h&&e(_p,{term:r,open:h,onClose:()=>p(!1),viewOnly:!0})]})}function _p({term:t,open:r,onClose:n,onSign:i,viewOnly:l=!1,title:c="Termos de Uso",signLabel:d="Li e concordo"}){const u=s(()=>t.file?function(e,a=""){const t=atob(e),r=[];for(let i=0;i<t.length;i+=512){const e=t.slice(i,i+512),a=new Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t);r.push(new Uint8Array(a))}const n=new Blob(r,{type:a});return URL.createObjectURL(n)}(t.file,t.type):null,[t.file,t.type]),m=o(()=>{u&&URL.revokeObjectURL(u),n()},[u,n]),h=o(()=>{t.hasUserSignature?m():i?.(t.id)},[t,i,m]),p=!l&&!t.hasUserSignature&&i;return e(Cs,{open:r,onOpenChange:e=>!e&&m(),children:a(Ps,{className:Ki("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[a("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[a("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e(xe,{className:"h-5 w-5 text-primary"}),c]}),a("div",{className:"flex items-center gap-2",children:[p&&e(es,{size:"sm",onClick:h,children:d}),e(es,{variant:"ghost",size:"icon",onClick:m,children:e(S,{className:"h-4 w-4"})})]})]}),e("div",{className:"flex-1 min-h-0",children:t.file&&u?e("iframe",{className:"h-full w-full border-0",src:u,title:c}):e("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:e("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function Sp(e){return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function Ap(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Dp({users:t,groups:r=[],value:n,onChange:l,disabled:c=!1,maxHeight:d=350,hideGroupFilter:u=!1,searchPlaceholder:m="Buscar usuário...",selectLabel:h="Selecionar",doneLabel:p="Concluir",allLabel:f="Todos",emptyLabel:g="Nenhum usuário selecionado",selectedLabel:v="selecionado",selectedPluralLabel:x="selecionados",className:b}){const[y,N]=i(!1),[w,C]=i(""),[k,_]=i(void 0),S=s(()=>new Set(n),[n]),A=s(()=>{let e=t;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),w){const a=Ap(w);e=e.filter(e=>Ap(e.name).includes(a)||Ap(e.email??"").includes(a))}return e},[t,k,w]),D=s(()=>y?A:t.filter(e=>S.has(e.id)),[y,A,t,S]),P=n.length,E=s(()=>A.length>0&&A.every(e=>S.has(e.id)),[A,S]),T=o(e=>{if(c)return;const a=S.has(e)?n.filter(a=>a!==e):[...n,e];l(a)},[n,S,l,c]),I=o(e=>{if(c)return;const a=new Set(A.map(e=>e.id));if(e){const e=new Set([...n,...a]);l(Array.from(e))}else l(n.filter(e=>!a.has(e)))},[n,A,l,c]),M=o(()=>{N(e=>!e),C(""),_(void 0)},[]);return a("div",{className:Ki("rounded-md border bg-muted/30",b),children:[(!c||P>0)&&a("div",{className:Ki("flex items-center justify-between px-4 py-2",!c&&"cursor-pointer hover:bg-muted/50"),onClick:c?void 0:M,children:[e("span",{className:"text-sm font-medium text-primary uppercase",children:!c&&(y?p:h)}),e("span",{className:"text-xs text-muted-foreground",children:P>0&&`${P} ${1===P?v:x}`})]}),a("div",{className:"px-4 pb-3",children:[y&&a("div",{className:"flex gap-3 mb-3",children:[!u&&r.length>0&&a(Ws,{value:k??"__all__",onValueChange:e=>_("__all__"===e?void 0:e),children:[e(Ys,{className:"w-[200px] h-9 text-sm",children:e(Gs,{placeholder:"Grupo de usuários"})}),a(Xs,{children:[e(Zs,{value:"__all__",children:"Todos os grupos"}),r.map(a=>e(Zs,{value:a.id,children:a.name},a.id))]})]}),a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-9 text-sm",placeholder:m,value:w,onChange:e=>C(e.target.value)})]})]}),!y&&0===P&&a("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[e(Sa,{className:"h-4 w-4 mr-2"}),g]}),y&&A.length>0&&a("div",{className:"flex items-center gap-2 mb-2",children:[e(ao,{checked:E,onCheckedChange:e=>I(!!e)}),e("span",{className:"text-sm",children:f})]}),D.length>0&&e(Ho,{style:{maxHeight:d},className:"pr-2",children:e("div",{className:"space-y-0.5",children:D.map(t=>a("div",{className:Ki("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",y&&!c&&"cursor-pointer hover:bg-accent/50"),onClick:y?()=>T(t.id):void 0,children:[y&&e(ao,{checked:S.has(t.id),onCheckedChange:()=>T(t.id),onClick:e=>e.stopPropagation()}),a(cu,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e(du,{src:t.avatar,alt:t.name}),e(uu,{className:"text-xs",children:Sp(t.name)})]}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"font-normal truncate",children:t.name}),t.email&&e("span",{className:"text-xs text-muted-foreground truncate",children:t.email})]})]},t.id))})}),y&&0===A.length&&e("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})}function Pp(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Ep(e){const a=new Set;if(!e)return a;for(const t of e)t.allowedIds?.forEach(e=>a.add(e)),t.inheritedIds?.forEach(e=>a.add(e));return a}function Tp({items:t,categories:r,value:n,onChange:l,readonly:c=!1,isLoading:d=!1,title:u="Permissões",addButtonLabel:m="Permitir",chipsTitle:h="Itens permitidos",chipsPlaceholder:p="Nenhum item selecionado",searchPlaceholder:f="Buscar...",selectPlaceholder:g="Selecione itens para adicionar...",itemInfoTemplate:v=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:x,disclaimerLink:b,onDisclaimerClick:y,className:N}){const[w,C]=i(r[0]?.id??""),[k,_]=i(""),[D,E]=i([]),[T,I]=i(!1),M=s(()=>Ep(n[w]),[n,w]),R=s(()=>function(e){const a=new Set;if(!e)return a;for(const t of e)t.inheritedIds?.forEach(e=>a.add(e));return a}(n[w]),[n,w]),L=s(()=>t.filter(e=>M.has(e.id)),[t,M]),z=s(()=>{const e=Pp(k);return t.filter(a=>!M.has(a.id)&&!(e&&!Pp(a.name).includes(e)))},[t,M,k]),F=s(()=>{const e={};for(const a of r)e[a.id]=Ep(n[a.id]).size;return e},[r,n]),U=o(e=>{C(e),E([]),_("")},[]),O=o(e=>{E(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),B=o(()=>{if(0===D.length)return;const e=[...n[w]??[]];for(const a of D){const r=t.find(e=>e.id===a),n=r?.group??"default",i=e.find(e=>e.context===n);i?i.allowedIds.includes(a)||(i.allowedIds=[...i.allowedIds,a]):e.push({context:n,allowedIds:[a],inheritedIds:[]})}l({...n,[w]:e}),E([]),_(""),I(!1)},[D,n,w,t,l]),$=o(e=>{if(R.has(e))return;const a=(n[w]??[]).map(a=>({...a,allowedIds:a.allowedIds.filter(a=>a!==e)}));l({...n,[w]:a})},[n,w,R,l]);return d?a("div",{className:Ki("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",N),children:[e("div",{className:"h-4 w-32 bg-muted rounded"}),e("div",{className:"h-9 w-full bg-muted rounded"}),e("div",{className:"h-20 w-full bg-muted rounded"})]}):e("div",{className:Ki("rounded-md border bg-muted/30",N),children:a("div",{className:"p-4 space-y-4",children:[a("div",{className:"space-y-2",children:[e("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:u}),a(Ws,{value:w,onValueChange:U,children:[e(Ys,{className:"h-9 text-sm",children:e(Gs,{})}),e(Xs,{children:r.map(t=>e(Zs,{value:t.id,children:a("span",{className:"flex items-center gap-2",children:[t.icon,t.name,F[t.id]>0&&e(no,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:F[t.id]})]})},t.id))})]})]}),!c&&a("div",{className:"flex gap-2",children:[a(Eo,{open:T,onOpenChange:I,children:[e(To,{asChild:!0,children:a(es,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[D.length>0?`${D.length} selecionado${D.length>1?"s":""}`:g,e(A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),a(Io,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[e("div",{className:"p-2 border-b",children:a("div",{className:"relative",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-8 text-sm",placeholder:f,value:k,onChange:e=>_(e.target.value)})]})}),e(Ho,{className:"max-h-[220px]",children:0===z.length?e("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):e("div",{className:"p-1",children:z.map(t=>{const r=D.includes(t.id);return a("div",{className:Ki("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>O(t.id),children:[e("div",{className:Ki("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&e(P,{className:"h-3 w-3"})}),a("div",{className:"flex flex-col min-w-0",children:[e("span",{className:"truncate",children:t.name}),null!=t.count&&e("span",{className:"text-xs text-muted-foreground",children:v(t.count)})]})]},t.id)})})})]})]}),a(es,{size:"sm",className:"h-9 gap-1",disabled:0===D.length,onClick:B,children:[e(Y,{className:"h-4 w-4"}),m]})]}),a("div",{className:"space-y-2",children:[e("p",{className:"text-sm font-medium",children:h}),e("div",{className:Ki("rounded-md border bg-background p-3 min-h-[60px]",c&&"bg-muted/50"),children:0===L.length?e("span",{className:"text-sm text-muted-foreground",children:p}):e("div",{className:"flex flex-wrap gap-1.5",children:L.map(t=>{const r=R.has(t.id);return a(no,{variant:r?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[t.name,!c&&!r&&e("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>$(t.id),children:e(S,{className:"h-3 w-3"})})]},t.id)})})}),c&&x&&a("p",{className:"text-xs text-muted-foreground",children:[e("span",{dangerouslySetInnerHTML:{__html:x}})," ",b&&y&&e("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:y,children:b})]})]})]})})}var Ip,Mp;(Mp=Ip||(Ip={}))[Mp.WaitingProcessing=1]="WaitingProcessing",Mp[Mp.Processing=2]="Processing",Mp[Mp.Completed=3]="Completed",Mp[Mp.Error=4]="Error",Mp[Mp.Expired=5]="Expired";const Rp={report:"Relatório",status:"Status",requestDate:"Data da solicitação",lastUpdate:"Última atualização",expirationDate:"Data de expiração",viewReport:"Visualizar relatório",searchPlaceholder:"Buscar relatório...",noResults:"Nenhum relatório encontrado",statusWaiting:"Aguardando",statusProcessing:"Processando",statusCompleted:"Concluído",statusError:"Erro",statusExpired:"Expirado"};function Lp(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function zp(e){return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Fp({requests:r,isLoading:n=!1,onGetReportUrl:l,formatDate:c=zp,labels:d,className:u}){const m={...Rp,...d},[h,p]=i(""),[f,g]=i(!1),[v,x]=i(""),[b,y]=i(""),[N,w]=i(null),C=s(()=>{if(!h)return r;const e=Lp(h);return r.filter(a=>Lp(a.reportName).includes(e))},[r,h]),k=o(async e=>{if(!N){w(e.id);try{const a=await l(e.id);a&&(x(a),y(e.reportName),g(!0))}finally{w(null)}}},[l,N]);return n?e("div",{className:Ki("space-y-3",u),children:Array.from({length:5}).map((a,t)=>e($o,{className:"h-12 w-full"},t))}):a(t,{children:[a("div",{className:Ki("space-y-3",u),children:[a("div",{className:"relative max-w-sm",children:[e(j,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{className:"pl-8 h-9 text-sm",placeholder:m.searchPlaceholder,value:h,onChange:e=>p(e.target.value)})]}),e(Ho,{className:"rounded-md border",children:a(Bl,{children:[e($l,{children:a(Wl,{children:[e(Hl,{className:"min-w-[140px]",children:m.report}),e(Hl,{className:"min-w-[150px]",children:m.status}),e(Hl,{className:"min-w-[160px]",children:m.requestDate}),e(Hl,{className:"min-w-[160px]",children:m.lastUpdate}),e(Hl,{className:"min-w-[160px]",children:m.expirationDate}),e(Hl,{className:"min-w-[140px]"})]})}),e(Vl,{children:0===C.length?e(Wl,{children:e(Gl,{colSpan:6,className:"text-center text-muted-foreground py-8",children:m.noResults})}):C.map(t=>{const r=function(e){return new Date>new Date(e.expirationDate)&&e.statusId===Ip.Completed?Ip.Expired:e.statusId}(t),n=function(a,t){switch(a){case Ip.WaitingProcessing:return{label:t.statusWaiting,icon:e(Pa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case Ip.Processing:return{label:t.statusProcessing,icon:e(Je,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case Ip.Completed:return{label:t.statusCompleted,icon:e(Da,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case Ip.Error:return{label:t.statusError,icon:e(U,{className:"h-3.5 w-3.5"}),variant:"danger"};case Ip.Expired:return{label:t.statusExpired,icon:e(Aa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(r,m),i=r===Ip.Completed,s=r===Ip.Expired;return a(Wl,{children:[e(Gl,{className:"font-medium",children:t.reportName}),e(Gl,{children:a(no,{variant:n.variant,className:Ki("gap-1",n.className),children:[n.icon,n.label]})}),e(Gl,{className:"text-sm",children:c(new Date(t.requestDate))}),e(Gl,{className:"text-sm",children:c(new Date(t.lastUpdate))}),e(Gl,{className:Ki("text-sm",s&&"text-destructive"),children:c(new Date(t.expirationDate))}),e(Gl,{children:a(es,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!i||N===t.id,onClick:()=>k(t),children:[N===t.id?e(E,{className:"h-4 w-4 animate-spin"}):e(me,{className:"h-4 w-4"}),m.viewReport]})})]},t.id)})})]})})]}),e(Cp,{open:f,onOpenChange:g,url:v,title:b})]})}function Up({reportApiUrl:a,parameters:t={},minHeight:r="80vh",...n}){const i=s(()=>{const e=`${a}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${e}?${r}`:e},[a,t]);return e(Cp,{...n,url:i,minHeight:r})}var jp,Op,Bp,$p,Vp,qp,Wp,Hp,Gp,Yp,Kp,Qp,Xp,Jp,Zp,ef,af,tf,rf,nf,sf,of,lf,cf,df,uf,mf,hf,pf,ff,gf,vf,xf,bf,yf,Nf,wf,Cf,kf,_f,Sf,Af,Df,Pf,Ef,Tf,If,Mf,Rf,Lf,zf;(Op=jp||(jp={})).Count="valuecount",Op.Sum="sum",Op.Average="average",Op.DistinctCount="valuecount_distict",Op.Max="max",Op.Min="min",(Bp||(Bp={})).ViewAllAnalysis="nes3j6wn",(Vp=$p||($p={})).RegisterDashboards="EeKs7CYA",Vp.RemoveDashboards="3GKZYOQ9",Vp.ViewAllDashboards="wYBdQNvZ",Vp.EditDashboards="bMFcbwv4",(Wp=qp||(qp={}))[Wp.Default=1]="Default",Wp[Wp.Compact=2]="Compact",(Gp=Hp||(Hp={}))[Gp.FiveSeconds=1]="FiveSeconds",Gp[Gp.TenSeconds=2]="TenSeconds",Gp[Gp.FifteenSeconds=3]="FifteenSeconds",Gp[Gp.ThirtySeconds=4]="ThirtySeconds",Gp[Gp.OneMinute=5]="OneMinute",Gp[Gp.ThreeMinutes=6]="ThreeMinutes",Gp[Gp.FiveMinutes=7]="FiveMinutes",Gp[Gp.TenMinutes=8]="TenMinutes",(Kp=Yp||(Yp={}))[Kp.Day=1]="Day",Kp[Kp.Month=2]="Month",Kp[Kp.Year=3]="Year",(Xp=Qp||(Qp={}))[Xp.Ascending=1]="Ascending",Xp[Xp.Descending=2]="Descending",(Zp=Jp||(Jp={}))[Zp.Label=1]="Label",Zp[Zp.Value=2]="Value",(af=ef||(ef={}))[af.LastSevenDays=1]="LastSevenDays",af[af.LastWeek=2]="LastWeek",af[af.LastMonth=3]="LastMonth",af[af.PreviousQuarter=4]="PreviousQuarter",af[af.PreviousSemester=5]="PreviousSemester",af[af.LastYear=6]="LastYear",af[af.SpecificPeriod=7]="SpecificPeriod",af[af.CurrentMonth=8]="CurrentMonth",af[af.CurrentSemester=9]="CurrentSemester",af[af.CurrentWeek=10]="CurrentWeek",af[af.CurrentYear=11]="CurrentYear",(rf=tf||(tf={}))[rf.Text=1]="Text",rf[rf.Area=2]="Area",rf[rf.Bar=3]="Bar",rf[rf.Column=4]="Column",rf[rf.StackedColumn=5]="StackedColumn",rf[rf.Line=6]="Line",rf[rf.List=7]="List",rf[rf.Numeric=8]="Numeric",rf[rf.Pareto=9]="Pareto",rf[rf.Pie=10]="Pie",rf[rf.RiskMatrix=11]="RiskMatrix",rf[rf.Burndown=12]="Burndown",rf[rf.PerformanceColumns=13]="PerformanceColumns",rf[rf.EvolutionLine=14]="EvolutionLine",(sf=nf||(nf={}))[sf.NotUpdate=1]="NotUpdate",sf[sf.FiveMinutes=2]="FiveMinutes",sf[sf.TenMinutes=3]="TenMinutes",sf[sf.FifteenMinutes=4]="FifteenMinutes",sf[sf.ThirtyMinutes=5]="ThirtyMinutes",sf[sf.OneHour=6]="OneHour",(lf=of||(of={}))[lf.NormalPage=1]="NormalPage",lf[lf.Carousel=2]="Carousel",(df=cf||(cf={}))[df.General=0]="General",df[df.Share=1]="Share",(mf=uf||(uf={}))[mf.NotShared=1]="NotShared",mf[mf.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",mf[mf.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(pf=hf||(hf={})).PtBr="pt-br",pf.EnUs="en",pf.EsEs="es",(gf=ff||(ff={}))[gf.Quantity=0]="Quantity",gf[gf.AllRisksList=1]="AllRisksList",(xf=vf||(vf={}))[xf.Five=5]="Five",xf[xf.Ten=10]="Ten",xf[xf.Fifteen=15]="Fifteen",xf[xf.Twenty=20]="Twenty",xf[xf.All=0]="All",xf[xf.Custom=-1]="Custom",(yf=bf||(bf={}))[yf.AlphabeticalAsc=1]="AlphabeticalAsc",yf[yf.AlphabeticalDesc=2]="AlphabeticalDesc",yf[yf.CountAsc=3]="CountAsc",yf[yf.CountDesc=4]="CountDesc",yf[yf.DateAsc=5]="DateAsc",yf[yf.DateDesc=6]="DateDesc",(wf=Nf||(Nf={}))[wf.Loading=0]="Loading",wf[wf.Loaded=1]="Loaded",wf[wf.Error=3]="Error",wf[wf.NoData=4]="NoData",wf[wf.Unavailable=5]="Unavailable",(kf=Cf||(Cf={}))[kf.Quantity=1]="Quantity",kf[kf.Percentage=2]="Percentage",kf[kf.QuantityPercentage=3]="QuantityPercentage",(Sf=_f||(_f={}))[Sf.Program=1]="Program",Sf[Sf.Project=2]="Project",Sf[Sf.Action=3]="Action",Sf[Sf.PerformanceProject=4]="PerformanceProject",Sf[Sf.PerformanceAction=5]="PerformanceAction",(Df=Af||(Af={})).OccurrenceActionPlans="xebGnSSq",Df.OccurrenceGeneral="UFws4AvH",Df.PlansActionPlans="Kux6CcVC",Df.PlansProgramProjects="UWjrp6Dw",Df.PlansIdeas="3g7vNm2w",Df.RisksGeneral="PZ4b6FhP",Df.RisksActionPlans="xZErDg57",Df.RisksAnalysis="UxsioMbH",Df.RisksIncidences="gNt5IJ2F",Df.MetrologyGeneral="4MfEPbRY",Df.MetrologyActivities="hdFM9XQW",Df.MetrologyServiceOrders="cIrVPdMv",Df.DecisionsGeneral="CopsnHDB",Df.DecisionsItems="qLFAayjx",Df.DecisionsActionPlans="RiQFpxdb",Df.FlowGeneral="AFV98JoG",Df.AuditGeneral="gON8LJPi",Df.AuditPlans="SsCNVOvr",Df.AuditPlansItems="OpPkCCFm",Df.AuditActionPlans="P1oGePhh",Df.CommonGeneral="VVfEzgMQ",Df.ActionPlans="C6Z4MgGa",Df.SuppliersEvaluations="fSCeS4mH",Df.SuppliersGeneral="8qPThkrD",Df.SuppliersEvaluationsCriteria="RiSIStdY",Df.SuppliersDocuments="Riua4jMa",Df.SuppliersMaterialsServices="UpEkatXH",Df.DocumentsGeneral="FRhhEX2J",Df.DocumentsPhysicalCopies="PZLtJ23h",Df.DocumentsObsolete="XDjbga14",Df.FmeaGeneral="aPwf4uPr",Df.FmeaActionPlans="vQ8PMrVX",(Ef=Pf||(Pf={}))[Ef.NotShared=1]="NotShared",Ef[Ef.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",Ef[Ef.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(If=Tf||(Tf={}))[If.All=1]="All",If[If.OnlyMine=2]="OnlyMine",If[If.Favorites=3]="Favorites",(Rf=Mf||(Mf={}))[Rf.Current=1]="Current",Rf[Rf.Inherent=2]="Inherent",(zf=Lf||(Lf={}))[zf.Default=1]="Default",zf[zf.Pastel=2]="Pastel",zf[zf.Vibrant=3]="Vibrant",zf[zf.Earth=4]="Earth",zf[zf.Ocean=5]="Ocean",zf[zf.Floral=6]="Floral",zf[zf.Night=7]="Night",zf[zf.Winter=8]="Winter",zf[zf.Spring=9]="Spring",zf[zf.Summer=10]="Summer",zf[zf.Fall=11]="Fall",zf[zf.Gray=12]="Gray",zf[zf.Brown=13]="Brown",zf[zf.Blue=14]="Blue",zf[zf.Yellow=15]="Yellow",zf[zf.Green=16]="Green",zf[zf.Purple=17]="Purple",zf[zf.Orange=18]="Orange",zf[zf.Pink=19]="Pink",zf[zf.Red=20]="Red";const Ff={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},Uf={advancedFilter:"analysisDashboardsListFilter"},jf=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Of=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function Bf(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return $f(e.items[0]?.keyDate)-$f(a.items[0]?.keyDate)})}function $f(e){if(!e)return 0;const[a,t]=e.split("/"),r=Ff[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function Vf(e){return null==e?.value||""===e.value.trim()}function qf(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function Wf(e){for(const a of Of)if(e[a])return e[a];return null}function Hf(e){return e?Gf(e).join("&"):null}function Gf(e){const a=[];for(const t of Object.keys(e)){const r=e[t];null!=r&&(r instanceof Date?a.push(`${t}=${r.toISOString()}`):Array.isArray(r)?r.forEach(e=>{a.push(...Gf({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const Yf=/^-?\d+(,\d{3})*(\.\d+)?$/;function Kf(e){return!!Yf.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function Qf(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const Xf=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function Jf(e){e.forEach(a=>{a.children=e.filter(e=>e.parentId===a.id)});const a=e.filter(e=>!e.parentId);return function e(a,t){a?.forEach(a=>{t(a),a.children&&e(a.children,t)})}(a,a=>{a.children=e.filter(e=>e.parentId===a.id)}),a}const Zf=new Set([tf.Text]),eg=new Set([tf.Text,tf.Numeric,tf.RiskMatrix,tf.Burndown,tf.PerformanceColumns]),ag=new Set([tf.Text,tf.RiskMatrix,tf.Burndown,tf.PerformanceColumns]);function tg({config:r,viewOnly:n=!1,complement:l,complementPosition:c="before-options",queryUrlBuilder:d,onRefresh:u,onExport:m,onToggleOnlyMine:h,className:p}){const[f,g]=i(r.onlyMine??!1),v=Zf.has(r.typeId),x=!eg.has(r.typeId),b=!ag.has(r.typeId),y=s(()=>{if(!r.jsonRules||r.typeId===tf.PerformanceColumns)return!1;try{const e=JSON.parse(r.jsonRules);return e?.rules?.rules?.length>0}catch{return!1}},[r.jsonRules,r.typeId]),N=s(()=>d?.(r)??"#",[d,r]),w=o(()=>{const e=!f;g(e),h?.(e)},[f,h]),C=[];return f&&C.push("Somente meus"),r.onlyLate&&C.push("Somente atrasados"),y&&C.push("Filtro avançado"),a("div",{className:Ki("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",p),children:[a("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===c&&l,a("div",{className:"flex min-w-0 flex-col",children:[a(So,{children:[e(Ao,{asChild:!0,children:e("span",{className:"block truncate",children:r.title})}),e(Do,{children:r.title})]}),C.length>0&&e("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:C.join(" | ")})]}),"after-title"===c&&l]}),!n&&a("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===c&&l,a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e(Ea,{className:"h-3.5 w-3.5"})})}),a(xo,{align:"end",className:"w-48",children:[r.canUpdate&&a(bo,{onClick:()=>r.onEdit?.(r.id),children:[e(W,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!v&&a(bo,{onClick:u,children:[e(Je,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&a(bo,{disabled:r.noData,onClick:m,children:[e(Ce,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!v&&a(bo,{disabled:!r.openQueryEnabled,onClick:()=>window.open(N,"_blank"),children:[e(Ze,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),b&&a(t,{children:[e(Co,{}),a(bo,{onClick:w,children:[f&&e(P,{className:"mr-2 h-3.5 w-3.5"}),!f&&e("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),r.canUpdate&&a(t,{children:[e(Co,{}),a(bo,{onClick:()=>r.onDuplicate?.(r.id),children:[e(ye,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),a(bo,{className:"text-destructive",onClick:()=>r.onRemove?.(r.id),children:[e(q,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===c&&l]})]})}function rg({config:t,queryUrl:r,className:n}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[e(Xe,{className:"h-12 w-12 text-muted-foreground/50"}),e("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),e("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),a("p",{className:"mt-2 text-xs",children:[r&&e("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),r&&t.canUpdate&&e("span",{className:"text-muted-foreground",children:" ou "}),t.canUpdate&&e("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>t.onEdit?.(t.id),children:"revisar o painel"})]})]})}function ng({panelType:t,className:r}){const n=t===tf.Burndown;return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[e(so,{className:"h-10 w-10 text-muted-foreground/40"}),n&&e("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function ig({hasRemovedColumn:t=!1,className:r}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[e("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:"Não há dados para exibir"}),e("p",{className:"text-sm text-muted-foreground lg:text-xs",children:t?"A coluna utilizada neste painel foi removida da consulta.":"A consulta não retornou itens para o seu perfil."})]})}function sg({onRemove:t,className:r}){return a("div",{className:Ki("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[e(Xe,{className:"h-12 w-12 text-muted-foreground/50"}),e("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),e("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),t&&e("p",{className:"mt-2 text-xs",children:e("button",{type:"button",className:"underline hover:text-foreground",onClick:t,children:"Remover painel"})})]})}const og={[jp.Count]:"Contagem",[jp.Sum]:"Soma",[jp.Average]:"Média",[jp.DistinctCount]:"Contagem distinta",[jp.Max]:"Valor máximo",[jp.Min]:"Valor mínimo"};function lg({config:t,state:r,value:n,label:i,viewOnly:s=!1,onClick:o,onRefresh:l,queryUrl:c,queryUrlBuilder:d,className:u}){const m=i??og[t.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=jf.includes(a.field),r=a.aggregationType===jp.Count||a.aggregationType===jp.DistinctCount;return t&&!r?Xf.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?r?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(n,t);return a("div",{className:Ki("flex h-full flex-col",u),children:[e(tg,{config:t,viewOnly:s,onRefresh:l,queryUrlBuilder:d}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&a("div",{className:Ki("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,children:[e("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:h}),m&&e("span",{className:"text-xs text-muted-foreground mt-1",children:m})]}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:c}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function cg({config:t,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:s,queryUrl:o,queryUrlBuilder:l,className:c}){const d=n??t.textTypeString??"";return a("div",{className:Ki("flex h-full flex-col",c),children:[e(tg,{config:t,viewOnly:i,onRefresh:s,queryUrlBuilder:l}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:d}}),r===Nf.Error&&e(rg,{config:t,queryUrl:o})]})}function dg({config:t,state:r,data:n=[],columns:i=[],viewOnly:l=!1,onRowClick:c,onRefresh:d,onExport:u,queryUrl:m,queryUrlBuilder:h,enableRowLinks:p=!0,className:f}){const g=s(()=>i.filter(e=>!1!==e.visible),[i]),v=o(e=>{if(c)c(e);else if(p){const a=Wf(e);a&&window.open(qf(a),"_blank")}},[c,p]);return a("div",{className:Ki("flex h-full flex-col",f),children:[e(tg,{config:t,viewOnly:l,onRefresh:d,onExport:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 overflow-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:e("tr",{children:g.map(a=>e("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:a.header||a.columnLabel||a.columnName},a.columnName))})}),e("tbody",{children:n.map((a,t)=>{const r=p&&!!Wf(a);return e("tr",{className:Ki("border-b border-border/50 transition-colors hover:bg-muted/30",(r||c)&&"cursor-pointer"),onClick:()=>v(a),children:g.map(t=>e("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:t.render?t.render(a[t.columnName],a):ug(a[t.columnName],t)},t.columnName))},t)})})]})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function ug(e,a){return null==e?"":e instanceof Date?"datetime"===a.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const mg=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function hg({config:t,variant:r,state:n,data:i=[],series:o,colors:l,categoryKey:c="key",yAxisFormat:d,viewOnly:u=!1,onPointClick:m,onRefresh:h,onExport:p,queryUrl:f,queryUrlBuilder:g,className:v}){const x=l?.length?l:t.hexColors?.length?t.hexColors:mg,b=s(()=>o?.length?o:[{dataKey:"value",name:t.title}],[o,t.title]),y="bar"===r,N="stacked-column"===r,w=s(()=>{if(d)return e=>d.replace("{value}",e.toLocaleString("pt-BR"))},[d]);return a("div",{className:Ki("flex h-full flex-col",v),children:[e(tg,{config:t,viewOnly:u,onRefresh:h,onExport:p,queryUrlBuilder:g}),n===Nf.Loading&&e(ng,{}),n===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:pg({variant:r,data:i,series:b,colors:x,categoryKey:c,isHorizontalBar:y,isStacked:N,yAxisTickFormatter:w,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:m})})}),n===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),n===Nf.Error&&e(rg,{config:t,queryUrl:f}),n===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function pg({variant:t,data:r,series:n,colors:i,categoryKey:s,isHorizontalBar:o,isStacked:l,yAxisTickFormatter:c,tooltipFormatter:d,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},h=e(Ut,{dataKey:o?void 0:s,type:o?"number":"category",...m,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?c:void 0}),p=e(jt,{dataKey:o?s:void 0,type:o?"category":"number",...m,width:o?100:60,tickFormatter:o?void 0:c}),f=e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=e(Bt,{formatter:d,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?e($t,{wrapperStyle:{fontSize:"11px"}}):null,x=u?(e,a)=>u(r[a],a):void 0;return"bar"===t||"column"===t||"stacked-column"===t?a(Vt,{data:r,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>e(qt,{dataKey:a.dataKey,name:a.name||a.dataKey,fill:a.color||i[t%i.length],stackId:l?a.stackId||"stack":void 0,radius:l?void 0:[2,2,0,0],onClick:x,cursor:u?"pointer":void 0},a.dataKey))]}):"area"===t?a(Wt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>{const r=a.color||i[t%i.length];return e(Ht,{type:"monotone",dataKey:a.dataKey,name:a.name||a.dataKey,stroke:r,fill:r,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:u?"pointer":void 0}},a.dataKey)})]}):a(Gt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,h,p,g,v,n.map((a,t)=>e(Yt,{type:"monotone",dataKey:a.dataKey,name:a.name||a.dataKey,stroke:a.color||i[t%i.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:u?"pointer":void 0}},a.dataKey))]})}const fg=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function gg({config:t,state:r,data:n=[],colors:i,viewOnly:o=!1,onSliceClick:l,onRefresh:c,onExport:d,queryUrl:u,queryUrlBuilder:m,className:h}){const p=i?.length?i:t.hexColors?.length?t.hexColors:fg,f=s(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=s(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return a("div",{className:Ki("flex h-full flex-col",h),children:[e(tg,{config:t,viewOnly:o,onRefresh:c,onExport:d,queryUrlBuilder:m}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Kt,{children:[e(Qt,{data:f,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:a})=>`${e??""}: ${(100*(a??0)).toFixed(0)}%`,labelLine:!0,onClick:l?(e,a)=>l(n[a],a):void 0,cursor:l?"pointer":void 0,children:f.map((a,t)=>e(Xt,{fill:p[t%p.length]},t))}),e(Bt,{formatter:e=>{const a="number"==typeof e?e:0,t=g>0?(a/g*100).toFixed(1):"0";return`${a.toLocaleString("pt-BR")} (${t}%)`}}),e($t,{wrapperStyle:{fontSize:"11px"}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:u}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function vg({config:t,state:r,data:n=[],barColor:i,lineColor:o="#e31a1c",viewOnly:l=!1,onPointClick:c,onRefresh:d,onExport:u,queryUrl:m,queryUrlBuilder:h,className:p}){const f=t.hexColors?.length?t.hexColors:["#1f78b4"],g=i??f[0],v=s(()=>{const e=[...n].sort((e,a)=>(a.value??0)-(e.value??0)),a=e.reduce((e,a)=>e+(a.value??0),0);let t=0;return e.map(e=>(t+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:a>0?Math.round(t/a*100):0}))},[n]);return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:l,onRefresh:d,onExport:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Jt,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),e(jt,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),e(jt,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),e(Bt,{formatter:(e,a)=>"% Acumulado"===a?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(qt,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:g,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),e(Yt,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function xg({config:t,state:r,data:n=[],executedLabel:i="Trabalho executado",plannedLabel:s="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:c=!1,onRefresh:d,queryUrl:u,queryUrlBuilder:m,className:h}){return a("div",{className:Ki("flex h-full flex-col",h),children:[e(tg,{config:t,viewOnly:c,onRefresh:d,queryUrlBuilder:m}),r===Nf.Loading&&e(ng,{panelType:tf.Burndown}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Wt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),e(jt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),e(Bt,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(Ht,{type:"monotone",dataKey:"executedPercentage",name:i,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),e(Ht,{type:"monotone",dataKey:"plannedPercentage",name:s,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:u}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function bg({config:t,state:r,data:n=[],executedLabel:i="Trabalho executado",plannedLabel:s="Trabalho planejado",executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:c=!1,onPointClick:d,onRefresh:u,queryUrl:m,queryUrlBuilder:h,className:p}){return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:c,onRefresh:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&e("div",{className:"flex-1 min-h-0 p-2",children:e(Ft,{width:"100%",height:"100%",children:a(Vt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[e(Ot,{strokeDasharray:"3 3",className:"stroke-border/50"}),e(Ut,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),e(jt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),e(Bt,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),e($t,{wrapperStyle:{fontSize:"11px"}}),e(qt,{dataKey:"executedWork",name:i,fill:o,radius:[2,2,0,0],onClick:d?(e,a)=>d(n[a],a):void 0,cursor:d?"pointer":void 0}),e(qt,{dataKey:"plannedWork",name:s,fill:l,radius:[2,2,0,0]})]})})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}function yg({config:t,state:r,rule:n,risks:i=[],matrixViewType:o=ff.Quantity,viewOnly:l=!1,onCellClick:c,onRiskClick:d,onRefresh:u,queryUrl:m,queryUrlBuilder:h,className:p}){const f=s(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=s(()=>{const e={};return i.forEach(a=>{const t=`${a.parameterYPosition}-${a.parameterXPosition}`;e[t]||(e[t]=[]),e[t].push(a)}),e},[i]);return a("div",{className:Ki("flex h-full flex-col",p),children:[e(tg,{config:t,viewOnly:l,onRefresh:u,queryUrlBuilder:h}),r===Nf.Loading&&e(ng,{}),r===Nf.Loaded&&n&&e("div",{className:"flex-1 overflow-auto p-4",children:a("div",{className:"flex gap-4 items-stretch min-w-fit",children:[e("div",{className:"flex items-center justify-center",children:e("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:n.name_y})}),a("div",{className:"flex-1",children:[a("div",{className:"flex mb-1",children:[e("div",{className:"w-16 shrink-0"}),e("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.threat_strategy_type_name}),!n.disable_opportunities&&e("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.opportunity_strategy_type_name})]}),f.map((t,r)=>a("div",{className:"flex",children:[e("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:t.name}),g.map((i,s)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,t),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(s,r);return a("div",{className:Ki("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(c||d)&&l.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:u},onClick:()=>l.length>0&&c?.(i,t,l),children:[o===ff.Quantity&&l.length>0&&a("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),o===ff.AllRisksList&&l.map(t=>a(So,{children:[e(Ao,{asChild:!0,children:e("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:e=>{e.stopPropagation(),d?.(t)},children:t.code})}),a(Do,{className:"max-w-[250px]",children:[a("p",{className:"font-medium",children:[t.code," - ",t.name]}),t.analysisDate&&a("p",{className:"text-xs mt-1",children:["Última análise: ",e("strong",{children:t.analysisDate})]}),t.strategy&&a("p",{className:"text-xs",children:["Estratégia: ",e("strong",{children:t.strategy})]}),t.resultName&&a("p",{className:"text-xs",children:["Criticidade: ",e("strong",{style:{backgroundColor:u},className:"px-1 rounded",children:t.resultName})]})]})]},t.code))]},i.position)})]},t.position)),a("div",{className:"flex",children:[e("div",{className:"w-16 shrink-0"}),g.map(a=>e("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:a.name},a.position))]}),e("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:n.name_x})]})]})}),r===Nf.NoData&&e(ig,{hasRemovedColumn:t.hasRemovedColumn}),r===Nf.Error&&e(rg,{config:t,queryUrl:m}),r===Nf.Unavailable&&e(sg,{onRemove:()=>t.onRemove?.(t.id)})]})}const Ng=Object.freeze({Translate:{toString(e){if(!e)return;const{x:a,y:t}=e;return"translate3d("+(a?Math.round(a):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:a,scaleY:t}=e;return"scaleX("+a+") scaleY("+t+")"}},Transform:{toString(e){if(e)return[Ng.Translate.toString(e),Ng.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function wg(e){switch(e){case tf.Bar:case tf.Column:case tf.Pie:case tf.List:case tf.Line:case tf.Area:case tf.Text:case tf.StackedColumn:return{x:4,y:2};case tf.Pareto:case tf.RiskMatrix:case tf.Burndown:case tf.PerformanceColumns:return{x:8,y:2};case tf.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function Cg(e){switch(Number(e)){case tf.Area:case tf.Bar:case tf.Column:case tf.Line:case tf.Numeric:case tf.Pie:case tf.Text:return{x:1,y:1};default:return{x:2,y:2}}}function kg({panel:t,columns:r,cellHeight:n,cellGap:i,allowDragging:o,children:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=pr({id:t.id,disabled:!o}),f=s(()=>({gridColumn:`${t.col+1} / span ${t.sizeX}`,gridRow:`${t.row+1} / span ${t.sizeY}`,minHeight:t.sizeY*n+(t.sizeY-1)*i+"px",transform:Ng.Transform.toString(m),transition:h,zIndex:p?50:void 0,opacity:p?.85:1}),[t,r,n,i,m,h,p]);return a("div",{ref:u,style:f,className:Ki("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",p&&"shadow-lg ring-2 ring-primary/20"),...c,children:[e("div",{className:Ki("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?d:{}}),e("div",{className:"h-full",children:l})]})}function _g({panels:t,columns:r=8,cellHeight:n=160,cellGap:l=10,allowDragging:c=!1,showGridLines:d=!1,renderPanel:u,onLayoutChange:m,className:h}){const[p,f]=i(t);s(()=>{f(t)},[t]);const g=or(lr(cr,{activationConstraint:{distance:8}})),v=s(()=>0===p.length?1:Math.max(...p.map(e=>e.row+e.sizeY)),[p]),x=s(()=>p.map(e=>e.id),[p]),b=o(e=>{const{active:a,over:t}=e;if(!t||a.id===t.id)return;const r=p.findIndex(e=>e.id===a.id),n=p.findIndex(e=>e.id===t.id);if(-1===r||-1===n)return;const i=[...p],s={...i[r]},o={...i[n]},l=s.col,c=s.row;s.col=o.col,s.row=o.row,o.col=l,o.row=c,i[r]=s,i[n]=o,f(i),m?.(i)},[p,m]),y=s(()=>({display:"grid",gridTemplateColumns:`repeat(${r}, 1fr)`,gridTemplateRows:`repeat(${v}, ${n}px)`,gap:`${l}px`}),[r,v,n,l]);return 0===p.length?a("div",{className:Ki("flex flex-col items-center justify-center py-16 text-center",h),children:[e("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),e("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):e(dr,{sensors:g,collisionDetection:ur,onDragEnd:b,children:e(mr,{items:x,strategy:hr,children:e("div",{style:y,className:Ki("relative w-full",d&&"bg-muted/30",h),children:p.map(a=>e(kg,{panel:a,columns:r,cellHeight:n,cellGap:l,allowDragging:c,children:u(a.id)},a.id))})})})}const Sg={[tf.Bar]:"bar",[tf.Column]:"column",[tf.StackedColumn]:"stacked-column",[tf.Area]:"area",[tf.Line]:"line",[tf.EvolutionLine]:"evolution-line"};function Ag({config:t,state:r,data:n,numericValue:i,listColumns:s,cartesianData:o,cartesianSeries:l,burndownData:c,performanceData:d,matrixRule:u,matrixRisks:m,onPanelClick:h}){const p=Sg[t.typeId];if(p)return e(hg,{config:t,variant:p,state:r,data:o,series:l});switch(t.typeId){case tf.Numeric:return e(lg,{config:t,state:r,value:i});case tf.Text:return e(cg,{config:t,state:r});case tf.List:return e(dg,{config:t,state:r,data:n,columns:s??[]});case tf.Pie:return e(gg,{config:t,state:r,data:n});case tf.Pareto:return e(vg,{config:t,state:r,data:n});case tf.Burndown:return e(xg,{config:t,state:r,data:c});case tf.PerformanceColumns:return e(bg,{config:t,state:r,data:d});case tf.RiskMatrix:return e(yg,{config:t,state:r,rule:u,risks:m??[]});default:return a("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",t.typeId,")"]})}}function Dg({dashboard:t,panels:r,pages:n,activePageId:l,canEdit:c=!1,isFullscreen:d=!1,isLoading:u=!1,getPanelData:m,onRefresh:h,onToggleFullscreen:p,onToggleFavorite:f,onEdit:g,onShare:v,onAddPanel:x,onEditPanel:b,onRemovePanel:y,onDuplicatePanel:N,onLayoutChange:w,onPageChange:C,toolbarActions:k,className:_}){const[S,A]=i(!1),D=t.idViewType===of.Carousel,P=s(()=>r,[r,D,l]),E=s(()=>P.map(e=>{const a=Cg(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:a.x,minSizeY:a.y}}),[P]),T=o(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:c,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:b,onRemove:y,onDuplicate:N}),[c,b,y,N]),I=o(()=>{S||u||(A(!0),h?.(),setTimeout(()=>A(!1),3e4))},[S,u,h]),M=o(t=>{const r=P.find(e=>e.id===t);if(!r)return null;const n=T(r),i=m?.(t)??{state:Nf.Loaded};return a("div",{className:"flex flex-col h-full",children:[e(tg,{config:n,onRefresh:()=>{}}),e("div",{className:"flex-1 min-h-0 p-2",children:e(Ag,{config:n,...i})})]})},[P,T,m,c,b,y,N]);return a("div",{className:Ki("flex flex-col h-full",d&&"fixed inset-0 z-50 bg-background",_),children:[a("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3 min-w-0",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:t.title}),t.responsibleName&&!d&&e("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:t.responsibleName})]}),a("div",{className:"flex items-center gap-1",children:[k,h&&e("button",{onClick:I,disabled:S||u,className:Ki("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:S?"Aguarde para atualizar novamente":"Atualizar",children:e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),p&&e("button",{onClick:p,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:d?"Sair do fullscreen":"Fullscreen",children:e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",d?{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),c&&!d&&v&&e("button",{onClick:v,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),f&&!d&&e("button",{onClick:f,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:t.isFavorite?"Remover favorito":"Favoritar",children:e("svg",{className:Ki("h-4 w-4",t.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),D&&n&&n.length>1&&e("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:n.map(a=>e("button",{onClick:()=>C?.(a.id),className:Ki("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",l===a.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:a.name||`Dashboard ${a.position}`},a.id))}),c&&!d&&x&&e("div",{className:"flex justify-center py-3",children:a("button",{onClick:x,className:Ki("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),u&&e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!u&&e("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:e(_g,{panels:E,allowDragging:c,showGridLines:c,renderPanel:M,onLayoutChange:w})})]})}function Pg(e,a=hf.PtBr){switch(a){case hf.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case hf.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function Eg(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const Tg=[{value:Tf.All,label:"Todos"},{value:Tf.OnlyMine,label:"Meus dashboards"},{value:Tf.Favorites,label:"Favoritos"}];function Ig({dashboards:r,limit:n,isLoading:l=!1,language:c=hf.PtBr,canAdd:d=!1,canEdit:u=!1,canRemove:m=!1,onOpen:h,onEdit:p,onShare:f,onDuplicate:g,onRemove:v,onAdd:x,onToggleFavorite:b,onRefresh:y,onSearch:N,onQuickFilterChange:w,toolbarExtra:C,className:k}){const[_,S]=i(""),[A,D]=i(Tf.All),[P,E]=i(null),T=o(e=>{S(e),N?.(e)},[N]),I=o(e=>{D(e),w?.(e)},[w]),M=s(()=>{let e=r;if(_){const a=_.toLowerCase();e=e.filter(e=>e.code?.toLowerCase().includes(a)||Pg(e,c).toLowerCase().includes(a)||e.responsibleName?.toLowerCase().includes(a))}switch(A){case Tf.OnlyMine:break;case Tf.Favorites:e=e.filter(e=>e.isFavorite)}return e},[r,_,A,c]);return a("div",{className:Ki("flex flex-col h-full",k),children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3",children:[e("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),n&&a("span",{className:"text-xs text-muted-foreground",children:["(",n.countDashboards,"/",n.maxDashboards,")"]})]}),a("div",{className:"flex items-center gap-2",children:[a("div",{className:"relative",children:[a("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"11",cy:"11",r:"8"}),e("path",{d:"m21 21-4.3-4.3"})]}),e("input",{type:"text",placeholder:"Buscar...",value:_,onChange:e=>T(e.target.value),className:Ki("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),C,d&&x&&a("button",{onClick:x,className:Ki("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),e("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:Tg.map(a=>e("button",{onClick:()=>I(a.value),disabled:l,className:Ki("px-3 py-1.5 text-sm rounded-md transition-colors",A===a.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:a.label},a.value))}),l&&e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!l&&e("div",{className:"flex-1 overflow-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:a("tr",{children:[e("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:e("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),e("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:a("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),e("th",{className:"w-12 px-3 py-2"})]})}),a("tbody",{children:[0===M.length&&e("tr",{children:e("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),M.map(r=>a("tr",{onClick:()=>h?.(r),className:Ki("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[e("td",{className:"px-3 py-2",children:e("button",{onClick:e=>{e.stopPropagation(),b?.(r)},className:"p-1 hover:bg-accent rounded transition-colors",children:e("svg",{className:Ki("h-4 w-4",r.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),e("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:r.code}),e("td",{className:"px-3 py-2 text-foreground font-medium",children:Pg(r,c)}),e("td",{className:"px-3 py-2 text-muted-foreground",children:r.responsibleName}),e("td",{className:"px-3 py-2 text-center",children:r.hasSharedIcon&&a("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e("circle",{cx:"9",cy:"7",r:"4"}),e("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),e("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:Eg(r.lastModified)}),e("td",{className:"px-3 py-2",children:e("span",{className:Ki("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",r.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:r.isActive?"Ativo":"Inativo"})}),e("td",{className:"px-3 py-2",children:a("div",{className:"relative",children:[e("button",{onClick:e=>{e.stopPropagation(),E(P===r.id?null:r.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:a("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"12",cy:"5",r:"1"}),e("circle",{cx:"12",cy:"12",r:"1"}),e("circle",{cx:"12",cy:"19",r:"1"})]})}),P===r.id&&a(t,{children:[e("div",{className:"fixed inset-0 z-40",onClick:()=>E(null)}),a("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[e("button",{onClick:e=>{e.stopPropagation(),E(null),h?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),u&&e("button",{onClick:e=>{e.stopPropagation(),E(null),p?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),u&&e("button",{onClick:e=>{e.stopPropagation(),E(null),f?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),e("button",{onClick:e=>{e.stopPropagation(),E(null),g?.(r)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),m&&a(t,{children:[e("div",{className:"my-1 border-t border-border"}),e("button",{onClick:e=>{e.stopPropagation(),E(null),v?.(r)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},r.id))]})]})})]})}const Mg=[{value:nf.NotUpdate,label:"Não atualizar"},{value:nf.FiveMinutes,label:"5 minutos"},{value:nf.TenMinutes,label:"10 minutos"},{value:nf.FifteenMinutes,label:"15 minutos"},{value:nf.ThirtyMinutes,label:"30 minutos"},{value:nf.OneHour,label:"1 hora"}],Rg=[{value:of.NormalPage,label:"Página normal"},{value:of.Carousel,label:"Carrossel"}],Lg=[{value:Hp.FiveSeconds,label:"5 segundos"},{value:Hp.TenSeconds,label:"10 segundos"},{value:Hp.FifteenSeconds,label:"15 segundos"},{value:Hp.ThirtySeconds,label:"30 segundos"},{value:Hp.OneMinute,label:"1 minuto"},{value:Hp.ThreeMinutes,label:"3 minutos"},{value:Hp.FiveMinutes,label:"5 minutos"},{value:Hp.TenMinutes,label:"10 minutos"}],zg=[{value:uf.NotShared,label:"Não compartilhado",description:"Somente o responsável terá acesso"},{value:uf.SharedWithAllCollaborators,label:"Compartilhado com todos os colaboradores da unidade",description:"Todos os colaboradores terão acesso"},{value:uf.SharedWithUsersGroupsPlacesCollaborators,label:"Compartilhado com grupos, locais e colaboradores",description:"Selecione grupos, locais e colaboradores específicos"}],Fg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function Ug({dashboard:t,initialTab:r=cf.General,isSaving:n=!1,isQualitfy:l=!1,users:c=[],groups:d=[],places:u=[],collaborators:m=[],onSave:h,onCancel:p,className:f}){const g=!!t,[v,x]=i(r),[b,y]=i({"pt-br":!!t?.titlePtBr||!g,en:!!t?.titleEnUs,es:!!t?.titleEsEs}),[N,w]=i(t?.titlePtBr??""),[C,k]=i(t?.titleEnUs??""),[_,S]=i(t?.titleEsEs??""),[A,D]=i(t?.responsibleId??""),[P,E]=i(t?.isActive??!0),[T,I]=i(t?.idUpdateTime??nf.NotUpdate),[M,R]=i(t?.idViewType??of.NormalPage),[L,z]=i(t?.idPageTime??Hp.FifteenSeconds),[F,U]=i(t?.idShare??uf.NotShared),[j,O]=i(t?.groups??[]),[B,$]=i(t?.places??[]),[V,q]=i(t?.collaborators??[]),W=M===of.Carousel,H=b["pt-br"]||b.en||b.es,G=s(()=>!!H&&(!(b["pt-br"]&&!N.trim())&&(!(b.en&&!C.trim())&&!(b.es&&!_.trim()))),[H,b,N,C,_]),Y=o(e=>{y(a=>({...a,[e]:!a[e]}))},[]),K=o(()=>{G&&!n&&h?.({titlePtBr:b["pt-br"]?N:"",titleEnUs:b.en?C:"",titleEsEs:b.es?_:"",responsibleId:A||void 0,isActive:P,idUpdateTime:T,idViewType:M,idPageTime:W?L:null,idShare:F,groups:F===uf.SharedWithUsersGroupsPlacesCollaborators?j:[],places:F===uf.SharedWithUsersGroupsPlacesCollaborators?B:[],collaborators:F===uf.SharedWithUsersGroupsPlacesCollaborators?V:[]})},[G,n,h,b,N,C,_,A,P,T,M,L,W,F,j,B,V]);return a("div",{className:Ki("flex flex-col h-full bg-background",f),children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[a("div",{className:"flex items-center gap-3",children:[e("h2",{className:"text-lg font-semibold text-foreground",children:g?"Editar Dashboard":"Novo Dashboard"}),g&&t&&e("span",{className:"text-sm text-muted-foreground",children:t.code})]}),a("div",{className:"flex items-center gap-2",children:[e("button",{onClick:p,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),a("button",{onClick:K,disabled:!G||n,className:Ki("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[n?e("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),a("div",{className:"flex border-b border-border bg-card",children:[e("button",{onClick:()=>x(cf.General),className:Ki("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",v===cf.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),e("button",{onClick:()=>x(cf.Share),className:Ki("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",v===cf.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),a("div",{className:"flex-1 overflow-auto p-6",children:[v===cf.General&&a("div",{className:"max-w-2xl space-y-6",children:[a("div",{className:"space-y-2",children:[e("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),e("div",{className:"flex gap-2",children:Fg.map(a=>e("button",{onClick:()=>Y(a.key),className:Ki("px-3 py-1 text-xs rounded-md border transition-colors",b[a.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:a.label},a.key))}),!H&&e("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),b["pt-br"]&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),e("input",{value:N,onChange:e=>w(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[N.length,"/200"]})]}),b.en&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),e("input",{value:C,onChange:e=>k(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[C.length,"/200"]})]}),b.es&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),e("input",{value:_,onChange:e=>S(e.target.value),maxLength:200,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),a("p",{className:"text-xs text-muted-foreground text-right",children:[_.length,"/200"]})]}),!t?.isStandard&&c.length>0&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),a("select",{value:A,onChange:e=>D(e.target.value),disabled:!g,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[e("option",{value:"",children:"Selecione..."}),c.map(a=>e("option",{value:a.id,children:a.name},a.id))]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),e("select",{value:T,onChange:e=>I(Number(e.target.value)),disabled:l,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Mg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]}),a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Situação"}),a("div",{className:"flex items-center gap-3 h-10",children:[e("button",{onClick:()=>E(!P),disabled:t?.isGeneralViewUse,className:Ki("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",P?"bg-primary":"bg-muted","disabled:opacity-50"),children:e("span",{className:Ki("inline-block h-4 w-4 rounded-full bg-white transition-transform",P?"translate-x-6":"translate-x-1")})}),e("span",{className:"text-sm text-foreground",children:P?"Ativo":"Inativo"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),e("select",{value:M,onChange:e=>R(Number(e.target.value)),disabled:l||W,className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Rg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]}),W&&a("div",{className:"space-y-1",children:[e("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),e("select",{value:L??"",onChange:e=>z(Number(e.target.value)),className:Ki("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:Lg.map(a=>e("option",{value:a.value,children:a.label},a.value))})]})]})]}),v===cf.Share&&a("div",{className:"max-w-2xl space-y-6",children:[a("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[a("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("path",{d:"M12 16v-4"}),e("path",{d:"M12 8h.01"})]}),e("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),e("div",{className:"space-y-3",children:zg.map(r=>a("label",{className:Ki("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",F===r.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",t?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[e("input",{type:"radio",name:"shareType",value:r.value,checked:F===r.value,onChange:()=>U(r.value),disabled:t?.isGeneralViewUse,className:"mt-1 accent-primary"}),a("div",{children:[e("p",{className:"text-sm font-medium text-foreground",children:r.label}),e("p",{className:"text-xs text-muted-foreground",children:r.description})]})]},r.value))}),F===uf.SharedWithUsersGroupsPlacesCollaborators&&a("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",j.length,")"]}),e("select",{multiple:!0,value:j,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);O(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:d.map(a=>e("option",{value:a.id,children:a.name},a.id))})]}),a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Locais (",B.length,")"]}),e("select",{multiple:!0,value:B,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);$(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:u.map(a=>e("option",{value:a.id,children:a.name},a.id))})]}),a("div",{className:"space-y-1",children:[a("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",V.length,")"]}),e("select",{multiple:!0,value:V,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);q(a)},className:Ki("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:m.map(a=>e("option",{value:a.id,children:a.name},a.id))})]})]})]})]})]})}function jg({dashboards:t,limit:r,generalView:n,language:l=hf.PtBr,isLoading:c=!1,canAdd:d=!1,canEdit:m=!1,canRemove:h=!1,canEditStandard:p=!1,activePanels:f=[],activePages:g=[],getPanelData:v,users:x=[],groups:b=[],places:y=[],collaborators:N=[],isSaving:w=!1,onOpen:C,onBackToList:k,onRefresh:_,onRefreshList:S,onToggleFavorite:A,onSave:D,onUpdate:P,onRemove:E,onDuplicate:T,onShare:I,onAddPanel:M,onEditPanel:R,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onSearch:U,onQuickFilterChange:j,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:V,viewToolbarActions:q,className:W}){const[H,G]=i({mode:"list"}),Y=B??H,K=o(e=>{$?$(e):G(e)},[$]),Q=s(()=>"view"===Y.mode||"edit"===Y.mode||"share"===Y.mode?t.find(e=>e.id===Y.dashboardId)??null:null,[t,Y]),[X,J]=i(!1),[Z,ee]=i(g[0]?.id);u(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),u(()=>{if("view"!==Y.mode||!Q||Q.idViewType!==of.Carousel||g.length<=1)return;const e=function(e){switch(e){case Hp.FiveSeconds:return 5e3;case Hp.TenSeconds:return 1e4;case Hp.FifteenSeconds:return 15e3;case Hp.ThirtySeconds:return 3e4;case Hp.OneMinute:return 6e4;case Hp.ThreeMinutes:return 18e4;case Hp.FiveMinutes:return 3e5;case Hp.TenMinutes:return 6e5;default:return 15e3}}(Q.idPageTime),a=setInterval(()=>{ee(e=>{const a=(g.findIndex(a=>a.id===e)+1)%g.length;return g[a]?.id})},e);return()=>clearInterval(a)},[Y,Q,g]);const ae=o(e=>{K({mode:"view",dashboardId:e.id}),ee(void 0),C?.(e)},[K,C]),te=o(()=>{K({mode:"list"}),J(!1),k?.()},[K,k]),re=o(()=>{K({mode:"create"})},[K]),ne=o(e=>{K({mode:"edit",dashboardId:e.id})},[K]),ie=o(e=>{K({mode:"share",dashboardId:e.id})},[K]),se=o(e=>{"edit"===Y.mode||"share"===Y.mode?P?.(Y.dashboardId,e):D?.(e)},[Y,D,P]),oe=o(()=>{"edit"===Y.mode||"share"===Y.mode?K({mode:"view",dashboardId:Y.dashboardId}):K({mode:"list"})},[Y,K]),le=o(()=>{Q&&A?.(Q)},[Q,A]),ce=o(()=>{Q&&ne(Q)},[Q,ne]),de=o(()=>{Q&&ie(Q)},[Q,ie]);return a("div",{className:Ki("flex flex-col h-full",W),children:["list"===Y.mode&&e(Ig,{dashboards:t,limit:r,isLoading:c,language:l,canAdd:d,canEdit:m,canRemove:h,onOpen:ae,onEdit:ne,onShare:ie,onDuplicate:T,onRemove:E,onAdd:re,onToggleFavorite:A,onRefresh:S,onSearch:U,onQuickFilterChange:j,toolbarExtra:V,className:"flex-1"}),"view"===Y.mode&&Q&&a("div",{className:"flex flex-col h-full",children:[!X&&a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[a("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),n?.dashboardId===Q.id&&a("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[a("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),e("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),m&&O&&n?.dashboardId!==Q.id&&e("button",{onClick:()=>O(Q.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),e(Dg,{dashboard:Q,panels:f,pages:g,activePageId:Z,canEdit:m||p&&!!Q.isStandard,isFullscreen:X,isLoading:c,getPanelData:v,onRefresh:_,onToggleFullscreen:()=>J(e=>!e),onToggleFavorite:le,onEdit:ce,onShare:de,onAddPanel:M,onEditPanel:R,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onPageChange:ee,toolbarActions:q,className:"flex-1"})]}),"create"===Y.mode&&a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:a("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),e(Ug,{users:x,groups:b,places:y,collaborators:N,isSaving:w,onSave:se,onCancel:oe,className:"flex-1"})]}),("edit"===Y.mode||"share"===Y.mode)&&Q&&a("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:a("button",{onClick:oe,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),e(Ug,{dashboard:Q,initialTab:"share"===Y.mode?cf.Share:cf.General,users:x,groups:b,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!p,onSave:se,onCancel:oe,className:"flex-1"})]})]})}const Og=({manager:r,columns:n,onEdit:i,onView:s,onToggleStatus:o,onDelete:l,renderActions:c,customRowActions:d,enableBulkActions:m=!1,onNew:h,newButtonLabel:p,showNewButton:f=!0,customActions:g=[],hideActionBar:v,showActionBar:x=!0,showSearch:b=!1,searchValue:y,onSearchChange:N,searchPlaceholder:w,bulkActions:C=[],onBulkDelete:k,filters:_,gridColumns:S=3,renderCard:A,viewMode:D,onViewModeChange:P,listCardRenderer:E,gridCardRenderer:T,showViewToggle:I=!1})=>{const{setSearchVisible:M}=zl(),R=void 0!==v?!v:x;u(()=>{if(!b)return M(!0),()=>M(!1)},[M,b]);const L=h||g.length>0||b||m||_||I,z=k||(()=>{r.bulkDelete?.(r.selectedIds)}),F=D||"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=R&&L?e(Pc,{onNew:h,newButtonLabel:p,showNewButton:f,showSearch:b,searchValue:y,onSearchChange:N,searchPlaceholder:w,showBulkActions:m,selectedCount:r.selectedIds.length,bulkActions:C,onBulkDelete:z,onClearSelection:r.clearSelection,customActions:g,filters:_,viewMode:F,onViewModeChange:P,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(Ql,{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(ac,{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:Ki("grid gap-4",j),children:r.entities.map(u=>{const h=(e=>U&&E?E(e):!U&&T?T(e):A?A(e):null)(u);return a(nc,{children:[e(ic,{asChild:!0,children:h?e("div",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),m?r.selectItem(u.id):i?.(u)},children:h}):e(is,{className:Ki("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(cs,{className:Ki("p-4",U&&"flex items-center gap-4 w-full"),children:[m&&e("div",{className:Ki(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:e(Ec,{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||s||c)&&e("div",{onClick:e=>e.stopPropagation(),children:c?c(u):e(yc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(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(Ec,{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:Ki("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||s||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(u):e(yc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(u):void 0,isActive:u.is_actived,customActions:d?d(u):[]})})]})]})]})})}),e(mc,{className:"w-[160px]",children:e(bc,{onEdit:i?()=>i(u):void 0,onDelete:l?()=>l(u):void 0,onToggleStatus:o?()=>o(u):void 0,isActive:u.is_actived,canDelete:!!l,customActions:d?d(u):[],renderAs:"context"})})]},u.id)})})})]})};function Bg({data:t,columns:r,sortField:n,sortDirection:i,onSort:o,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u,className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:x=!0,onColumnResize:b,enableColumnReorder:y=!1,onReorderColumns:N,storageKey:w}){const{t:C}=tt(),k=u||C("no_items_found","Nenhum item encontrado"),{columnWidths:_,isDragging:S,activeColumn:A,handleMouseDown:D}=Cc({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:w?`${w}-columns`:void 0,onResize:b,enabled:x}),P=Mc({enabled:y&&!!N,onReorder:N??(()=>{})}),E=s(()=>{if(x)return r.map(e=>`${_[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,x,_]);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($o,{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:k})})}):e("div",{className:"flex-1 overflow-auto "+(S?"select-none":""),children:a(Bl,{className:m,children:[e($l,{className:"sticky top-0 bg-background z-10",children:a(Wl,{children:[h&&e(Hl,{className:"w-[40px]",children:e(ao,{checked:v,onCheckedChange:g,"aria-label":C("select_all","Selecionar todos")})}),r.map((t,r)=>{const s=x&&!1!==t.resizable,l=A===String(t.key),c=y&&!!N,d=c?P.getDragProps(r):{},u=P.dragFromIndex===r,m=P.dragOverIndex===r&&P.dragFromIndex!==r;return a(Hl,{className:Ki(t.className,"relative transition-opacity",t.sortable&&"cursor-pointer",c&&P.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:E[r]},...d,children:[t.sortable&&o?a("button",{onClick:()=>o(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(h=String(t.key),n!==h?null:e("asc"===i?ae:te,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:t.header}),s&&e(rc,{direction:"horizontal",onMouseDown:e=>D(String(t.key),e),isDragging:l})]},String(t.key));var h}),c&&e(Hl,{className:"w-[80px] text-right",children:C("actions","Ações")})]})}),e(Vl,{children:t.map(t=>a(Wl,{onClick:()=>l?.(t),className:(l?"cursor-pointer":"")+" relative",children:[h&&e(Gl,{children:e(ao,{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(Gl,{className:a.className,children:e(tc,{children:a.render?a.render(t):String(t[a.key]??"-")})},String(a.key))),c&&e(Gl,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})}function $g({onEdit:t,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:o=!0,canDelete:l=!0,customActions:c=[],renderAs:d="dropdown",variant:u="default"}){const{t:m}=tt(),h=s(()=>{const e=[];return t&&o&&e.push({key:"edit",icon:B,label:m("edit","Editar"),onClick:t,variant:"default"}),n&&e.push({key:"toggle-status",icon:i?$:V,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,o,l,c,m]);return 0===h.length?null:"dropdown"===d?e(_o,{delayDuration:200,children:a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:e(_,{size:"compact"===u?14:16})})}),e(xo,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:h.map(t=>t.disabled?a(Po,{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(bo,{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(es,{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 Vg({searchValue:t="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:s=!0,layout:o="horizontal"}){const{t:l}=tt(),c=t||n.length>0;return a("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&a("div",{className:"relative flex-1 min-w-[200px]",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{type:"text",placeholder:l("search","Pesquisar"),value:t,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((a,t)=>e("div",{className:"vertical"===o?"w-full":"",children:a},t)),s&&c&&i&&a(es,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function qg(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 Wg({children:a,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:s,onDropCell:o,className:l}){return e(Gl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},className:l,children:a})}function Hg({item:r,level:n,columns:i,nameKey:s,iconComponent:o,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m="default",enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:x,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:C}){const k=l.has(r.id),_=(r.children?.length??0)>0,S=24*n,D="inline"===m,P=v===r.id||p?.has(r.id)&&v&&p?.has(v),E=x===r.id&&v!==r.id,T=p?.has(r.id)??!1,I={itemId:r.id,enableDrag:g,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w};return a(t,{children:[a(Wl,{className:Ki(d&&"cursor-pointer",D&&"group",P&&"opacity-40",E&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:d?()=>d(r):void 0,children:[e(Wg,{...I,children:a("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[h&&e(ao,{checked:T,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:"⠿"}),_?e("button",{onClick:e=>{e.stopPropagation(),c(r.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:e(k?A:z,{className:"h-4 w-4"})}):e("div",{className:"w-6 shrink-0"}),o??e(qe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"truncate",children:String(r[s]??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],s=t.render?t.render(r,n):null!=i?String(i):"—";return e(Wg,{...I,className:Ki("text-center",t.className),children:t.hoverContent?a(Fu,{openDelay:200,children:[e(Uu,{asChild:!0,children:e("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:s})}),e(ju,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:t.hoverContent(r)})]}):s},String(t.key))}),u&&e(Wg,{...I,className:"text-right",children:e("div",{onClick:e=>e.stopPropagation(),className:Ki("flex items-center justify-end gap-1",D&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(r)})})]}),_&&k&&r.children.map(a=>e(Hg,{item:a,level:n+1,columns:i,nameKey:s,iconComponent:o,expandedIds:l,onToggleExpand:c,onRowClick:d,renderActions:u,rowActionsVariant:m,enableSelection:h,selectedIds:p,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:x,onDragStartCell:b,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:C},a.id))]})}function Gg({onDrop:t,isDragOver:r,onDragOver:n,onDragLeave:i,label:s}){return a("div",{className:Ki("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(Ta,{className:"h-4 w-4"}),s??"Tornar Raiz"]})}function Yg({data:t,columns:r,nameKey:s,nameHeader:l="Nome",iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,actionsHeader:f="",rowActionsVariant:g="default",isLoading:v,emptyMessage:x="Nenhum registro encontrado.",className:b,enableSelection:y,selectedIds:N,onSelectItem:w,onSelectAll:C,isAllSelected:k,enableRowDrag:_,onMoveNode:S,onMoveNodes:A,rootDropLabel:D,actionsWidth:P=20,nameMinWidth:E=200}){const[T,I]=i(null),[M,R]=i(null),[L,z]=i(!1),[F,U]=i(1),j=d(null),O=d([]),B=d(null),$=n.useMemo(()=>new Set(N??[]),[N]),V=n.useMemo(()=>{if(!T||!t)return new Set;const e=O.current.length>0?O.current:[T],a=function(e,a){const t=new Set;for(const r of a)qg(e,r).forEach(e=>t.add(e));return t}(t,e);return e.forEach(e=>a.add(e)),a},[T,t]),q=d(V);q.current=V;const W=o(()=>{j.current=null,O.current=[],B.current=null,I(null),R(null),z(!1),U(1)},[]),H=o((e,a)=>{e.length>1&&A?A(e,a):1===e.length&&S?.(e[0],a)},[S,A]),G=o((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=o((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",q.current.has(e)?R(null):(B.current=e,R(e))},[]),K=o((e,a)=>{a.preventDefault(),a.stopPropagation();const t=q.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=o(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=o(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",z(!0)},[]),J=o(e=>{_&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[_]),Z=o(e=>{if(!_)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]);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(qe,{className:"h-10 w-10 text-muted-foreground/50"}),e("p",{className:"text-sm text-muted-foreground",children:x})]});const ee=null!==T;return a("div",{className:Ki("border rounded-lg overflow-hidden relative",b),onDragOver:J,onDrop:Z,onDragLeave:_?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(R(null),z(!1))}:void 0,children:[_&&ee&&e(Gg,{onDrop:Q,isDragOver:L,onDragOver:X,onDragLeave:()=>z(!1),label:D}),a(Bl,{children:[e($l,{children:a(Wl,{children:[e(Hl,{className:"text-left",style:{minWidth:E},children:a("div",{className:"flex items-center gap-2",children:[y&&e(ao,{checked:k??!1,onCheckedChange:()=>C?.()}),l]})}),r.map(a=>e(Hl,{className:Ki("text-center",a.className),style:a.width?{width:a.width}:void 0,children:a.header},String(a.key))),p&&e(Hl,{className:"text-right",style:{width:P},children:f})]})}),e(Vl,{children:t.map(a=>e(Hg,{item:a,level:0,columns:r,nameKey:s,iconComponent:c,expandedIds:u,onToggleExpand:m,onRowClick:h,renderActions:p,rowActionsVariant:g,enableSelection:y,selectedIds:$,onSelectItem:w,enableRowDrag:_,draggedId:T,dragOverId:M,onDragStartCell:G,onDragEndCell:W,onDragOverCell:Y,onDropCell:K,dragCount:F},a.id))})]})]})}function Kg(e){const a=pt();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 Qg(e,a){const t=Kg({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Xg=n.memo(({variant:r="card",className:i="",selectedUnit:o,onUnitChange:l})=>{const{user:c,companies:d,alias:u,isAuthenticated:m,logout:h,switchUnit:p}=zl(),{role:f}=Xd(),g=f?.name||null,v=d?.[0]||null,x=u?d?.find(e=>e.alias===u):v,b=d||[],y=o||x||v||v,N=s(()=>{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]),w=s(()=>{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]),k=n.useMemo(()=>{if(!b?.length)return[];const e=new Map;b.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===y?.alias),r=a.filter(e=>e.alias!==y?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[b,y?.alias]);if(!m||!c)return null;return"dropdown"===r?a(co,{children:[e(uo,{asChild:!0,children:e(es,{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:y?.name||"N/A"})]}),a(cu,{className:"w-8 h-8 border border-primary-foreground/30",children:[N&&e(du,{src:N,alt:c.name||"Foto do usuário"}),e(uu,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:w||e(qe,{className:"h-4 w-4"})})]}),e(A,{className:"h-4 w-4"})]})})}),a(xo,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[a(po,{children:[a(go,{children:[e(Je,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(vo,{children:k.map(t=>a(bo,{onClick:()=>C(t),className:t.alias===y?.alias?"bg-muted":"",children:[e(aa,{className:"mr-2 h-4 w-4"}),t.name,t.alias===y?.alias&&e(no,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e(Co,{}),a(bo,{onClick:h,children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):a(is,{className:i,children:[e(ss,{children:e(os,{className:"text-lg",children:"Informações do Usuário"})}),a(cs,{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(cu,{className:"w-10 h-10",children:[N&&e(du,{src:N,alt:c.name||"Foto do usuário"}),e(uu,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:w||e(qe,{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: ",y?.name||"N/A"]})]})]}),y&&e("div",{className:"mt-3",children:a("div",{className:"flex items-center space-x-2",children:[e(aa,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:y.name})]})}),k.length>1&&a("div",{className:"mt-2",children:[a("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",k.length]}),a("div",{className:"flex flex-wrap gap-1",children:[k.slice(0,3).map(a=>e(no,{variant:a.alias===y?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>C(a),children:a.name},a.alias)),k.length>3&&a(no,{variant:"outline",className:"text-xs",children:["+",k.length-3]})]})]})]}),{}),e(us,{}),a(es,{variant:"outline",onClick:h,size:"sm",className:"w-full",children:[e(ta,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Jg=l({});function Zg({children:a,config:t}){const r=s(()=>{const e=wr(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return e(Jg.Provider,{value:r,children:a})}function ev(){return c(Jg)}function av(){const e=ft(),{navigation:a}=ev();return tv(a,e.pathname)}function tv(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 rv(e,a){const[t,r]=i(e),n=d(),s=o(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return u(()=>(s(),n.current=setTimeout(()=>{r(e)},a),s),[e,a,s]),[t,s]}function nv({appName:r}){const[n,s]=i(!1);return a(t,{children:[a("div",{className:"flex items-center justify-between w-[258px]",children:[e("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:e("img",{src:zr.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/80 hover:text-primary-foreground/60 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(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return a(t,{children:[s," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(r)})})]}),e(Zd,{open:n,onOpenChange:s})]})}const iv=m(function({actions:t}){const r=ft(),n=pt(),{navigation:s,appName:l}=ev(),c=tv(s,r.pathname),{metadata:d,headerActions:m}=xd(),{setOpenMobile:h}=Vm(),{companies:p,alias:f,isSearchVisible:g,clearSearch:v,refreshData:x,switchUnit:b}=zl(),y=f?p?.find(e=>e.alias===f)||p?.[0]||null:p?.[0]||null,[N,w]=mt(),C=o(e=>{const{pathname:a,search:t,hash:i}=r;if(f){const r=a.split("/"),s=r.indexOf(f);if(s>=0)return r[s]=e.alias,void n(r.join("/")+t+i)}b(e)},[f,r,n,b]),[k,_]=i(()=>N.get("search")||""),[A,D]=rv(k,_r.debounceDelay);u(()=>{if(!g)return;const e=new URLSearchParams(N);A?(e.set("search",A),e.set("page","1")):e.delete("search"),w(e)},[A,w,g]);const P=s?.find(e=>e.path===r.pathname)||s?.find(e=>r.pathname.startsWith(e.path+"/")),E=d.title||c,T=d.subtitle||P?.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(es,{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(Ia,{size:20})}),e("div",{className:"hidden md:flex items-center flex-shrink-0",children:e(nv,{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(z,{className:"h-3 w-3"}),t.href?e(vt,{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:E})}),e("div",{className:"text-sm text-primary-foreground/70 truncate",children:T})]}),g&&a("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[a("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(ts,{placeholder:"Pesquisar",value:k,onChange:e=>(e=>{_(e)})(e.target.value),className:"w-full pl-10 pr-8"}),k&&e(es,{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:()=>{D(),_("");const e=new URLSearchParams(N);e.delete("search"),e.delete("page"),w(e)},title:"Limpar busca",children:e(S,{size:14})})]}),e(es,{variant:"outline",size:"sm",onClick:x,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(es,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Gi(import.meta.env.VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e(cp,{}),e("div",{className:"text-sm",children:e(Xg,{variant:"dropdown",selectedUnit:y,onUnitChange:C})})]})]})})}),sv=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>lt({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function ov({config:r,isCollapsed:n=!1,isDisabled:i=!1,className:s}){const{actions:o,triggerLabel:l="Criar",triggerIcon:c=Y,variant:d="button"}=r;if(!o||0===o.length)return null;if("split-button"===d){const t=o[0],r=t.icon||c,l=o.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=e(es,{onClick:t.onClick,disabled:i||t.disabled,className:Ki("justify-center px-2 w-full",s),variant:"outline",size:"default",children:e(r,{className:"h-4 w-4 shrink-0"})});return a(So,{children:[e(Ao,{asChild:!0,children:n}),e(Do,{side:"right",children:e("p",{children:t.label})})]})}return e(Xh,{label:t.label,onClick:t.onClick,icon:r,actions:l,variant:"outline",disabled:i||t.disabled,className:Ki("w-full",s),menuAlign:"start"})}const u=(r,i,s=!1)=>a(t,{children:[r,!n&&i&&e("span",{className:"truncate",children:i}),!n&&s&&e(A,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const t=o[0],r=t.icon||c,l=i||t.disabled,d=e(es,{onClick:t.onClick,disabled:l,className:Ki("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:u(e(r,{className:"h-4 w-4 shrink-0"}),t.label)});return n?a(So,{children:[e(Ao,{asChild:!0,children:d}),e(Do,{side:"right",children:e("p",{children:t.label})})]}):d}const m=e(es,{disabled:i,className:Ki("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:u(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return a(co,{children:[e(uo,{asChild:!0,children:n?a(So,{children:[e(Ao,{asChild:!0,children:m}),e(Do,{side:"right",children:e("p",{children:l})})]}):m}),e(xo,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(t=>{const r=t.icon;return a(bo,{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 lv="forlogic-sidebar-pinned",cv=()=>{try{const e=localStorage.getItem(lv);return!!e&&JSON.parse(e)}catch{return!1}};function dv({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:s,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","290px"))},[c,l]);const g=o(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),s?.(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,s]),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 uv=l(void 0);function mv({children:a}){const[t,r]=i(new Set),[n,l]=i(!1),c=o(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),d=o(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=o(e=>{l(e)},[]),m=s(()=>t.size>0||n,[t,n]),h=s(()=>({openModals:t,hasOpenModal:m,registerModal:c,unregisterModal:d,setHasOpenModal:u}),[t,m,c,d,u]);return e(uv.Provider,{value:h,children:a})}function hv(){const e=c(uv);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function pv(){const{hasOpenModal:e}=hv();return e}function fv({config:t,customContent:r,resizable:n=!1,minWidth:s=224,maxWidth:l=384}={}){const{open:c,setOpen:d,setOpenMobile:m}=Vm(),h=ft(),{alias:p,user:f}=zl(),{appName:g}=ev(),{hasOpenModal:v}=hv(),[x,b]=i(cv),y=Ol(),N=o(()=>{y&&m(!1)},[y,m]),w=n?dv({minWidth:s,maxWidth:l,storageKey:"app-sidebar-width",isOpen:c}):null;u(()=>{d(!!x)},[x,d]);const C=e=>h.pathname===e||h.pathname.startsWith(e+"/");return a(Wm,{collapsible:"icon",className:Ki("app-sidebar bg-background border-r border-border flex flex-col",c?"px-3":"px-1.5"),style:w&&c?{width:`${w.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[t?.moduleActions&&t.moduleActions.actions.length>0&&e("div",{className:"py-3",children:e(_o,{children:e(ov,{config:t.moduleActions,isCollapsed:!c,isDisabled:v})})}),e(Zm,{className:Ki(t?.moduleActions&&t.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||e(eh,{className:"p-0",children:e(rh,{children:e(nh,{className:"gap-1",children:e(_o,{children:t?.navigation?.map((t,r)=>{const n=({item:t,index:r})=>{const i=`${t.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:s=!0,isLoading:o}=sv({key:i,enabled:Boolean(t.permissionCheck&&p&&f?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),l=t.permissionCheck&&!s,d=o?E:l?pe:t.icon;l||t.complementaryText;return t.children&&t.children.length>0?c?e(Md,{defaultOpen:!0,className:"group/collapsible",children:a(ih,{children:[e(Rd,{asChild:!0,children:e(oh,{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(z,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),e(Ld,{children:e(uh,{children:t.children.map((a,t)=>e(n,{item:a,index:t},a.path))})})]})},t.path):e(ih,{children:a(So,{children:[e(Ao,{asChild:!0,children:e("div",{className:Ki("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(Do,{side:"right",children:e("p",{children:t.label})})]})},t.path):e(ih,{children:l||o?a(So,{children:[e(Ao,{asChild:!0,children:c?e(oh,{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 "+(o?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text",children:t.label})]})}):e("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e(d,{className:"h-4 w-4 "+(o?"animate-spin":"")})})}),e(Do,{side:"right",children:e("p",{children:o?"Verificando acesso...":"Acesso restrito"})})]}):c?e(oh,{asChild:!0,isActive:C(t.path),size:"default",children:a(vt,{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(So,{children:[e(Ao,{asChild:!0,children:e(vt,{to:t.path,onClick:N,className:Ki("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(Do,{side:"right",children:e("p",{children:t.label})})]})},t.path)};return e(n,{item:t,index:r},t.path)})})})})})}),!y&&e("div",{className:Ki("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:a(So,{children:[e(Ao,{asChild:!0,children:e("button",{onClick:()=>{const e=!x;b(e),(e=>{try{localStorage.setItem(lv,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?Ee:z,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),e(Do,{side:"right",children:e("p",{children:c?"Recolher":"Expandir"})})]})}),n&&w&&c&&e("div",{ref:w.dragRef,onMouseDown:w.handleMouseDown,className:Ki("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",w.isDragging&&"bg-primary/40")})]})}const gv=m(function({children:t,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const l=s(()=>r||e(fv,{config:n}),[r,n]),c=s(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),m=d(null),h=d(null),p=o(()=>{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(Zg,{config:n,children:e(vd,{children:e(qm,{defaultOpen:!1,style:c,children:a("div",{ref:h,className:"flex flex-col h-screen w-full overflow-hidden",children:[i&&e("div",{ref:m,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:e(iv,{})}),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 min-h-0 overflow-y-auto bg-muted/30",children:t})})]})]})})})})});function vv({open:r,appName:n}){const[s,o]=i(!1);return a(t,{children:[e(Qm,{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:()=>o(!0),children:e("img",{src:zr.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:()=>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(A,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return a(t,{children:[s," ",a("span",{className:"whitespace-nowrap",children:[i," ",e(A,{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:()=>o(!0),children:e("img",{src:zr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),e(Zd,{open:s,onOpenChange:o})]})}function xv({title:t,subtitle:r,children:n,className:i,hasHeader:s=!0}){const o=t||r;return a("div",{className:Ki("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[s&&o&&a("div",{className:"px-6 py-4 border-b border-border/50",children:[t&&e("h2",{className:"text-xl font-semibold text-foreground",children:t}),r&&e("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&e("div",{className:Ki("p-6",!s&&o&&"pt-4"),children:n})]})}function bv({breadcrumbs:t,children:n,className:i}){return a("div",{className:Ki("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[t&&t.length>0&&e(mu,{className:"mb-4",children:e(hu,{children:t.map((n,i)=>{const s=i===t.length-1;return a(r.Fragment,{children:[i>0&&e(vu,{}),e(pu,{children:s||!n.href?e(gu,{children:n.label}):n.asChild&&n.children?e(fu,{asChild:!0,children:n.children}):e(fu,{asChild:!0,children:e(vt,{to:n.href||"/",children:n.label})})})]},`${n.label}-${i}`)})})}),e("div",{className:"space-y-6",children:n})]})}const yv=(e={})=>{const{enabled:a=!0}=e,{alias:t}=zl();return lt({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=pl(),{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(!vl.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function Nv({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:s,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),x=d(0),b=o(e=>c[e]??a,[c,a]),y=o((e,t)=>{l&&(t.preventDefault(),t.stopPropagation(),p(!0),g(e),v.current=t.clientY,x.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,x.current+a));m(e=>{const a={...e,[f]:n};return s?.(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,s]),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=o(()=>{m({}),n&&localStorage.removeItem(n),s?.({})},[n,s]);return{rowHeights:c,isDragging:h,activeRow:f,handleMouseDown:y,resetHeights:N,getRowHeight:b}}function wv(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,x=0===c,b=c===v-1,y=a[c],N=v>1?(c+1)/v*100:100,w=o(()=>!y?.canProceed||y.canProceed(),[y]),C=s(()=>w(),[w,u]),k=s(()=>!x&&!y?.disableBack,[x,y]),_=o(e=>{m(a=>({...a,...e}))},[]),S=o((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=o(()=>{d(t),m(r),p(!1),g(!1),l?.()},[t,r,l]),D=o(async()=>{if(w()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[w,f,u,n]),P=o(async()=>{w()&&!h&&(b?await D():d(e=>Math.min(e+1,v-1)))},[w,h,b,v,D]),E=o(()=>{k&&!h&&d(e=>Math.max(e-1,0))},[k,h]),T=o(e=>{e<0||e>=v||h||(e<=c||e===c+1)&&d(e)},[c,v,h]),I=o(e=>{p(e)},[]);return{currentStep:c,currentStepConfig:y,data:u,isFirstStep:x,isLastStep:b,isLoading:h,isCompleting:f,next:P,back:E,goTo:T,canProceed:C,canGoBack:k,setData:_,updateField:S,reset:A,complete:D,setLoading:I,progress:N,stepIndex:c,totalSteps:v}}const Cv=()=>{const{locale:e,timezone:a}=Pd(),t=Ti;return{formatDatetime:r=>qi(r,t,a,e),formatDate:t=>Wi(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class kv{static async sendEmail(e){const a=pl(),{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 _v=kv;function Sv({open:t,onOpenChange:r,placeId:n,placeName:o,onMakeManager:l,onMakeMembers:c,currentManagerId:d,currentMemberIds:u=[]}){const[m,h]=i([]),[p,f]=i(!1),[g,v]=i(""),{data:x=[],isLoading:b}=Vc({enabled:t}),y=s(()=>{let e=[...x];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},[x,g]),N=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},w=1===m.length,C=m.length>0;return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"max-w-2xl",variant:"form",children:[e(Es,{showSeparator:!0,children:a(Ms,{className:"flex items-center gap-2",children:[e(Sa,{className:"h-5 w-5"}),"Gerenciar Acessos - ",o]})}),a(Ts,{children:[a("div",{className:"relative mb-4",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(ts,{placeholder:"Pesquisar...",value:g,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Ho,{className:"h-[400px] pr-4",children:b?e("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e($o,{className:"h-16 w-full"},t))}):0===y.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(Sa,{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:y.map(t=>{const r=t.userId===d,n=u.includes(t.userId||""),i=m.includes(t.userId||"");return a("div",{className:Ki("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(ao,{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(Ma,{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(Is,{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)"]})}),w&&l&&a(es,{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(Ma,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&c&&a(es,{onClick:async()=>{if(c&&0!==m.length){f(!0);try{await c(m,n),h([])}finally{f(!1)}}},disabled:p,children:[e(Ra,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function Av({place:t,level:r=0,manageAccessConfig:n}){const[s,o]=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(Md,{open:s,onOpenChange:o,children:[a("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[d?a(Rd,{className:"flex items-center gap-2 flex-1",children:[e(z,{className:Ki("h-4 w-4 transition-transform shrink-0",s&&"rotate-90")}),e(aa,{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(aa,{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(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(no,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e($g,{customActions:[{label:"Gerenciar Acessos",icon:Ve,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Ld,{children:t.subPlaces.map(a=>e(Av,{place:a,level:r+1,manageAccessConfig:n},a.id))})]}),0===r&&e(us,{}),n&&e(Sv,{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 Dv({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(Av,{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(aa,{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 Pv=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=xl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=cl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status}`);throw e.status=s.status,e}return s.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 xl.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 dl.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return dl.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Ev(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 Tv(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 Iv(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Mv(){const{alias:e,isAuthenticated:a}=zl(),t=cl.getAccessToken(),{data:r=[]}=Vc({enabled:!0});return lt({queryKey:["leadership",e],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=pl(),{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 s={};r.forEach(e=>{s[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>{const a=n.filter(a=>a.id_leader===e.id_user);return{...e,name:s[e.id_user]?.name||"[Usuário inativo]",email:s[e.id_user]?.email||"",subordinatesCount:a.length,subordinateNames:a.map(e=>s[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=s[e],t=n.filter(a=>a.id_leader===e);o.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:a?.name||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>s[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),Tv(o)},enabled:!!t&&!!e&&a&&r.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const Rv="common";function Lv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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 Ov(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(Rv).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]}),C.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{C.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function zv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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(Rv).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 Ov(t,e,c.id_user,a.id_leader)}const s=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(Rv).from("leaders").insert(s).select();if(l)throw l;return o},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{C.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Fv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(Rv).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 Ov(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:s}=await t.schema(Rv).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(s)throw s;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{C.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function Uv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(Rv).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{C.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function jv(){const{alias:e}=zl(),a=ot(),t=pl(),{t:r}=tt();return ct({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),s=await Promise.all([t.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:o,error:l},{data:c,error:d}]=s;if(l)throw l;if(d)throw d;const u=o||[],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 Ov(t,e,r.id_user,a,r.id);for(const y of v){if(y.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Ov(t,e,y.id_user,a)}const x=[];if(p.length){const a=p.map(e=>e.id);x.push(t.schema(Rv).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);x.push(t.schema(Rv).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}));x.push(t.schema(Rv).from("leaders").insert(r))}const b=(await Promise.all(x)).find(e=>e?.error);if(b?.error)throw b.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{C.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Ov(e,a,t,r,n){const{data:i,error:s}=await e.schema(Rv).from("leaders").select("id, id_user, id_leader").eq("alias",a).eq("is_removed",!1);if(s)throw s;const o=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=o.find(e=>e.id_user===c);c=e?.id_leader||null}}var Bv=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,s=r.path.join(".");if(!t[s])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[s]={message:o.message,type:o.code}}else t[s]={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[s].types,c=l&&l[r.code];t[s]=Ka(s,a,t,n,c?[].concat(c,r.message):r.message)}e.shift()}return t},$v=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,s){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&gr({},i),{errors:{},values:t.raw?r:e}})}catch(l){return s(l)}return o&&o.then?o.then(void 0,s):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:vr(Bv(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(s){return Promise.reject(s)}}};const Vv=fr.object({id_leader:fr.string().nullable(),id_users:fr.array(fr.string()).min(1,"Selecione pelo menos um liderado")}),qv=fr.object({id_leader:fr.string().nullable(),id_users:fr.array(fr.string())});function Wv({value:t,onChange:r,excludeUserIds:n=[],error:s}){const{data:o=[],isLoading:l}=Vc(),[c,m]=i(""),h=d(null),p=d(0),f=o.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||"",s=a.userName||a.userEmail||"";return i.localeCompare(s)});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(E,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[e(ts,{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(ao,{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(ns,{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)"]}),s&&e("p",{className:"text-sm text-destructive",children:s})]})}function Hv({leader:r,prefilledLeaderId:n,onSuccess:s}){const{alias:o}=zl(),l=!!r,c=r?.id.startsWith("virtual-"),d=zv(),m=Lv(),h=Fv(),p=jv(),f=Uv(),{data:g=[]}=Mv(),{data:v=[]}=Vc(),[x,b]=i(""),y=Iv(g).map(e=>e.id_user),N=l?Iv(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],w=Qa({resolver:$v(l?qv:Vv),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});u(()=>{if(r){const e=Iv(g).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);w.reset({id_leader:r.id_leader||null,id_users:e})}else n?w.reset({id_leader:n,id_users:[]}):w.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,g]);const C=d.isPending||m.isPending||h.isPending||p.isPending||f.isPending,k=w.watch("id_leader"),_=w.watch("id_users"),S=l?[r.id_user,...y.filter(e=>e!==r.id_user&&!_.includes(e)&&!N.includes(e))]:[k,...y.filter(e=>!_.includes(e))].filter(Boolean);return a("form",{onSubmit:w.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})}s?.()}catch(a){}}),className:"space-y-4",children:[l&&a("div",{children:[e(ns,{children:"Líder"}),e(ts,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||"[Usuário inativo]",disabled:!0,className:"bg-muted"})]}),a("div",{children:[e(ns,{children:"Superior Imediato"}),a(Ws,{value:k||"none",onValueChange:e=>w.setValue("id_leader","none"===e?null:e),children:[e(Ys,{children:e(Gs,{placeholder:"Selecione..."})}),a(Xs,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(ts,{placeholder:"Buscar superior...",value:x,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),a(Ho,{className:"h-[200px]",children:[e(Zs,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const a=l?e.userId!==r.id_user:!_.includes(e.userId),t=!x||e.userName?.toLowerCase().includes(x.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(Zs,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${o}`),w.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:w.formState.errors.id_leader.message})]}),a("div",{children:[e(ns,{children:"Subordinados *"}),e(Wv,{value:_,onChange:e=>w.setValue("id_users",e),excludeUserIds:S,error:w.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),a("div",{className:"flex items-center justify-between gap-2",children:[e(es,{type:"submit",disabled:C||!l&&0===_.length,children:C&&!f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Atualizando...":"Salvando..."]}):l?"Atualizar":"Criar"}),l&&!k&&0===_.length&&a(ms,{children:[e(hs,{asChild:!0,children:e(es,{type:"button",variant:"destructive",disabled:C,className:"ml-auto",children:f.isPending?a(t,{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):a(t,{children:[e(q,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),a(gs,{children:[a(vs,{children:[e(bs,{children:"Confirmar remoção"}),e(ys,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),a(xs,{children:[e(ws,{children:"Cancelar"}),e(Ns,{onClick:async()=>{if(r)try{await f.mutateAsync(r.id),s?.()}catch(e){}},children:"Remover"})]})]})]})]})]})}function Gv({open:t,onOpenChange:r,leader:n,prefilledLeaderId:i,title:s}){return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{variant:"form",className:"sm:max-w-[500px]",children:[e(Es,{showSeparator:!0,children:e(Ms,{children:s})}),e(Ts,{children:e(Hv,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Yv="leadership-expanded-nodes",Kv=(e,a)=>{try{localStorage.setItem(`${Yv}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Qv({unassociatedUsers:r=[],onAssociateUser:n,onMoveNode:l,onMoveNodes:c,columns:d,nameHeader:m="Líder",rootDropLabel:h="Tornar Líder Raiz"}={}){const{alias:p}=zl(),{data:f,isLoading:g,error:v,refetch:x}=Mv(),b=Fv(),y=Lv(),[N,w]=i(()=>p?(e=>{try{const a=localStorage.getItem(`${Yv}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(p):new Set),[C,k]=i([]),[_,S]=i(new Set),[D,P]=i(!0),[E,T]=i(!1),[I,M]=i(),[R,L]=i(null),F=s(()=>f?Iv(f):[],[f]),U=s(()=>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(`${Yv}-${p}`)){const e=f.map(e=>e.id),a=new Set(e);w(a),Kv(p,a)}}},[f,p]);const B=o(e=>{w(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),p&&Kv(p,t),t})},[p]),$=o(()=>{if(O){const e=new Set;w(e),p&&Kv(p,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));w(e),p&&Kv(p,e)}},[O,F,p]),V=o(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),q=o(()=>{k(j?[]:U)},[j,U]),H=o(e=>{S(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),G=o(e=>F.find(a=>a.id===e),[F]),K=o((e,a)=>{if(l)return void l(e,a);const t=r.find(a=>a.id===e);if(t){if(n){const e=a?G(a):null;n(t.id,e?.id_user||null)}else y.mutate({id_user:t.id,id_leader:a&&G(a)?.id_user||null});return}const i=G(e);if(!i)return;const s=a?G(a):null;b.mutate({id:i.id,id_leader:s?.id_user||null})},[l,r,n,G,b,y]),Q=o((e,a)=>{c?c(e,a):(e.forEach(e=>K(e,a)),k([]))},[c,K]),X=o(e=>{M(e),L(null),T(!0)},[]),J=o(()=>{M(void 0),L(null),T(!0)},[]),Z=o(()=>{T(!1),M(void 0),L(null)},[]),ee=o((e,a)=>{const t=_.has(e)&&_.size>1?Array.from(_):[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"},[_]),ae=s(()=>[{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(qe,{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(es,{onClick:()=>x(),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(es,{size:"sm",onClick:J,children:[e(Y,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e(es,{size:"sm",variant:"outline",onClick:$,children:a(t,O?{children:[e(A,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[e(z,{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(Sa,{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(Yg,{data:f||[],columns:te,nameKey:"name",nameHeader:m,expandedIds:N,onToggleExpand:B,iconComponent:e(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:V,onSelectAll:q,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(es,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>X(a),children:e(W,{className:"h-4 w-4"})})}),r.length>0&&a("div",{className:"border rounded-lg overflow-hidden",children:[a("button",{type:"button",onClick:()=>P(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(D?A:z,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e(Ra,{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,")"]}),_.size>0&&a("span",{className:"text-xs text-primary ml-1",children:["(",_.size," selecionado",_.size>1?"s":"",")"]}),e("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),D&&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:Ki("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",_.has(t.id)&&"bg-primary/5"),children:[e(ao,{checked:_.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(qe,{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(Gv,{open:E,onOpenChange:Z,leader:I,prefilledLeaderId:R,title:I?"Editar Nome":R?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${p}`)]})}function Xv(e){const[a,t]=i(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:s,onSuccess:o,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...s,...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 C.success("Sucesso",{description:"Arquivo enviado com sucesso"}),o?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw C.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 C.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),C.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw C.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Jv(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 Zv(e,a){const t=Jv(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function ex(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function ax(e,a){const t=ex(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function tx(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function rx(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function nx(e,a,t){switch(a||rx(e)){case"youtube":return Zv(e,t);case"vimeo":return ax(e,t);default:return e}}function ix({value:r,onChange:n,onSubmit:o,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:x}=Xv({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:b,uploading:y}=Xv({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=s(()=>rx(h.videoUrl||tx(h.embedCode)||""),[h.videoUrl,h.embedCode]),w=(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(ns,{children:"Tipo de entrada"}),a(Ws,{value:h.inputType||"url",onValueChange:e=>w("inputType",e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"url",children:"URL"}),e(Zs,{value:"upload",children:"Upload de arquivo"}),e(Zs,{value:"embed",children:"Código embed"})]})]})]}),"upload"===h.inputType&&c&&a("div",{className:"space-y-2",children:[e(ns,{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(es,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:x,children:a(t,x?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{children:"Código embed"}),e(to,{placeholder:"Cole o código embed aqui",value:h.embedCode||"",onChange:e=>w("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&a("div",{className:"space-y-2",children:[e(ns,{children:"Thumbnail"}),a("div",{className:"flex gap-2",children:[e(ts,{type:"url",placeholder:"URL da thumbnail",value:h.thumbnail||"",onChange:e=>w("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 b(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(es,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:a(t,y?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{htmlFor:"title",children:"Título"}),e(ts,{id:"title",placeholder:"Título do vídeo",value:h.title||"",onChange:e=>w("title",e.target.value)})]}),a("div",{className:"flex gap-6",children:[a("div",{className:"flex items-center gap-2",children:[e(ao,{id:"autoplay",checked:h.autoplay||!1,onCheckedChange:e=>w("autoplay",!0===e)}),e(ns,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),a("div",{className:"flex items-center gap-2",children:[e(ao,{id:"controls",checked:!1!==h.controls,onCheckedChange:e=>w("controls",!0===e)}),e(ns,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Preview"}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=h.videoUrl||tx(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?Zv(t,h.autoplay):ax(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(es,{variant:"outline",onClick:l,children:"Cancelar"}),e(es,{onClick:()=>{h.videoUrl||h.embedCode?o(h):C.error("Erro",{description:"Nenhum vídeo selecionado"})},disabled:!(h.videoUrl||h.embedCode),children:"Salvar"})]})]})}function sx({content:t,className:r="",style:n}){const i=t.videoUrl||tx(t.embedCode)||"";if(!i)return null;const s=rx(i);return e(is,{className:`overflow-hidden my-4 ${r}`,style:n,children:a(cs,{className:"p-0",children:["file"===s?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"===s?Zv(i,t.autoplay):ax(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 ox({value:r,onChange:n,onSubmit:s,onCancel:o,uploadFunction:l,deleteFunction:c,uploadOptions:u}){const[m,h]=i(r||{alignment:"center",allowDownload:!1}),p=d(null),{upload:f,uploading:g}=Xv({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(ns,{children:"URL"}),a("div",{className:"flex gap-2",children:[e(ts,{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(es,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:a(t,g?{children:[e(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[e(we,{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(ns,{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(ns,{htmlFor:"caption",children:"Legenda"}),e(to,{id:"caption",placeholder:"Legenda",value:m.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"alt",children:"Texto Alternativo"}),e(ts,{id:"alt",placeholder:"Texto Alternativo",value:m.alt||"",onChange:e=>v("alt",e.target.value)})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Alinhamento"}),a(Ws,{value:m.alignment||"center",onValueChange:e=>v("alignment",e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"left",children:"Esquerda"}),e(Zs,{value:"center",children:"Centro"}),e(Zs,{value:"right",children:"Direita"})]})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"width",children:"Largura"}),e(ts,{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(ns,{htmlFor:"height",children:"Altura"}),e(ts,{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(ao,{id:"allowDownload",checked:m.allowDownload||!1,onCheckedChange:e=>v("allowDownload",!0===e)}),e(ns,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),a("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(es,{variant:"outline",onClick:o,children:"Cancelar"}),e(es,{onClick:()=>{m.imageUrl?s(m):C.error("Erro",{description:"Nenhuma imagem selecionada"})},disabled:!m.imageUrl,children:"Salvar"})]})]})}function lx({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 cx(e,a){return e/a}function dx(e,a,t,r){const n=cx(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 ux(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 mx(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 hx(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function px(){const{alias:e}=zl(),[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=pl(),{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 s=o(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=pl(),{data:i,error:s}=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(s)throw s;return t(i),i},[e]);return{config:a,isLoading:r,saveConfig:s}}const fx=import.meta.env.VITE_SUPABASE_URL,gx=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function vx(e,a,t){const r=cl.getSupabaseToken(),n={"Content-Type":"application/json",apikey:gx};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${fx}/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 xx={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await vx(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 vx(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let bx=null;function yx(){return window.Clicksign?Promise.resolve():bx||(bx=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)}),bx)}const Nx="clicksign-container";function wx({signerId:t,environment:r="sandbox",onSign:n,onError:s,onClose:o}){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),yx().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(Nx),a.on("loaded",function(){m(!1)}),a.on("signed",function(){n?.()}),a.on("resized",function(e){const a=e,t=document.getElementById(Nx);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),a.on("error",function(e){m(!1),s?.(e instanceof Error?e:new Error("Erro no widget de assinatura"))}),a.on("closed",function(){o?.()}),l.current=a}).catch(a=>{e||(p("Falha ao carregar o script de assinatura."),m(!1),s?.(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(E,{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:Nx,style:{height:"600px"}})]})}function Cx({documentKey:t,signerEmail:r,signerName:n,keySigner:s,environment:l,onSign:c,onError:m}){const h=d(null),[p,f]=i("loading"),[g,v]=i(null),x="production"===l?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",b=(()=>{const e=new URLSearchParams({email:r,display_name:n||"",disable_preview:"0"});return s&&e.set("key_signer",s),`${x}/${t}?${e.toString()}`})(),y=o(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",y,!1),()=>{window.removeEventListener("message",y,!1)}),[y]);const N=o(()=>{"loading"===p&&f("ready")},[p]);return"error"===p?a(ud,{variant:"danger",className:"my-4",children:[e(md,{children:"Erro ao carregar documento"}),e(hd,{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(E,{className:"h-5 w-5 animate-spin"}),e("span",{className:"text-sm",children:"Carregando documento..."})]})}),e("iframe",{ref:h,id:"d4sign-container",src:b,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:N})]})}function kx({file:t,onDocumentSigned:r,onError:n,showEventLog:s=!1}){const{user:l,alias:c}=zl(),{config:m,isLoading:h}=px(),{t:p}=tt(),[f,g]=i(null),[v,x]=i(!1),[b,y]=i(null),[N,w]=i("sandbox"),[k,_]=i("clicksign"),[S,A]=i(null),[D,P]=i(null),[T,I]=i(!1),[M,R]=i(0),[L,z]=i(!1),[F,U]=i([]),j=d(null),O=d(null),B=o(e=>{s&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[s]),$=o(async e=>{if(g(e),y(null),A(null),P(null),B(`Arquivo selecionado: ${e.name}`),c&&l){x(!0);try{const a=m?.provider??"clicksign";_(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 xx.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}),w(i.environment),_(i.provider||a),"d4sign"===a?(B("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),y(i.document_id),C.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)),y(i.signer_id),C.success(p("sign_doc_sent","Documento enviado! Assine abaixo."))):(B("AVISO: Nenhum signer ID disponível."),C.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"),C.error(p("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):(B(`Erro: ${t}`),C.error(t)),n?.(e)}finally{x(!1)}}},[c,l,B,n,m]);u(()=>{t&&c&&l&&!h&&t!==O.current&&(O.current=t,$(t))},[t,c,l,h,$]);const V=o(async()=>{if(!S||!c)return;I(!0),R(0),z(!1),B("Buscando documento assinado...");for(let a=1;a<=6;a++){R(a),B(`Tentativa ${a}/6...`);try{const e=await xx.getSignedDocument({alias:c,envelopeId:S.envelope_id,documentId:S.document_id,provider:k});if(e.download_url)return B("Documento assinado disponível para download"),P(e.download_url),void I(!1)}catch(e){B(`Erro na tentativa ${a}: ${e instanceof Error?e.message:"Erro desconhecido"}`)}a<6&&(B("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}B("Não foi possível obter o documento assinado após 6 tentativas."),I(!1),z(!0)},[S,c,B,k]),q=o(async()=>{B("Documento assinado com sucesso!"),C.success(p("sign_signed_success","Documento assinado com sucesso!")),y(null),S&&c&&(r?.({success:!0,provider:k,envelope_id:S.envelope_id,document_id:S.document_id,signer_id:b||"",environment:N}),await V())},[B,r,S,b,c,N,k,V]);if(!c)return e(is,{className:"border-amber-200 bg-amber-50",children:e(cs,{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"===k?"D4Sign":"Clicksign",H=()=>s&&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&&!b&&(D||T||L)?a("div",{className:"space-y-4",children:[e(is,{className:"border-green-200 bg-green-50",children:a(cs,{className:"flex flex-col items-center gap-4 py-8",children:[e(Da,{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})]}),T?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(E,{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}...`)})]}):D?e(es,{asChild:!0,variant:"default",className:"gap-2",children:a("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[e(Ce,{className:"h-4 w-4"}),p("sign_download_signed","Baixar documento assinado")]})}):L?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(es,{variant:"secondary",className:"gap-2",onClick:V,children:[e(Je,{className:"h-4 w-4"}),p("sign_try_again","Tentar novamente")]})]}):null]})}),e(H,{})]}):b?a("div",{className:"space-y-4",children:["d4sign"===k?e(Cx,{documentKey:b,signerEmail:S?.signer_email||l?.email||"",signerName:l?.name,keySigner:S?.key_signer,environment:N,onSign:q,onError:n}):e(wx,{signerId:b,environment:N,onSign:q,onError:n}),e(H,{})]}):t&&(v||h)?e(is,{children:a(cs,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{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):C.error(p("sign_select_pdf","Selecione um arquivo PDF"))}}),e(is,v?{children:a(cs,{className:"flex items-center justify-center gap-3 py-10",children:[e(E,{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(cs,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[e(we,{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 _x({onSaved:t}){const{config:r,isLoading:n,saveConfig:s}=px(),{t:o}=tt(),[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(E,{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:o("sign_configured","Assinatura digital configurada para esta unidade")})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[e(U,{className:"h-4 w-4"}),e("span",{children:o("sign_not_configured","Assinatura digital ainda não configurada para esta unidade")})]}),a(is,{children:[e(ss,{children:e(os,{className:"text-base",children:o("sign_config_title","Configuração de Assinatura Digital")})}),e(cs,{children:a("form",{onSubmit:async e=>{if(e.preventDefault(),l.trim()){p(!0);try{await s(l.trim(),d),C.success(o("sign_config_saved","Configuração de assinatura salva com sucesso")),t?.()}catch(a){C.error(o("sign_config_save_error","Erro ao salvar configuração de assinatura"))}finally{p(!1)}}else C.error(o("sign_api_key_required","Informe a API Key do provedor de assinatura"))},className:"space-y-4",children:[a("div",{className:"space-y-2",children:[e(ns,{htmlFor:"sign-api-key",children:"API Key"}),e(ts,{id:"sign-api-key",type:"password",placeholder:o("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(ns,{children:o("sign_environment","Ambiente")}),a(Ws,{value:d,onValueChange:e=>m(e),children:[e(Ys,{children:e(Gs,{})}),a(Xs,{children:[e(Zs,{value:"sandbox",children:"Sandbox (Testes)"}),e(Zs,{value:"production",children:"Produção"})]})]})]}),a(es,{type:"submit",disabled:h,children:[h&&e(E,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config","Atualizar Configuração"):o("sign_save_config","Salvar Configuração")]})]})})]})]})}var Sx,Ax,Dx,Px,Ex,Tx,Ix,Mx,Rx,Lx;(Ax=Sx||(Sx={}))[Ax.waitingStart=1]="waitingStart",Ax[Ax.running=2]="running",Ax[Ax.effectivenessCheck=3]="effectivenessCheck",Ax[Ax.done=4]="done",Ax[Ax.suspended=5]="suspended",Ax[Ax.canceled=6]="canceled",(Px=Dx||(Dx={}))[Px.low=0]="low",Px[Px.medium=1]="medium",Px[Px.high=2]="high",(Tx=Ex||(Ex={}))[Tx.plan=2]="plan",Tx[Tx.occurrence=3]="occurrence",Tx[Tx.risk=4]="risk",Tx[Tx.decisions=5]="decisions",Tx[Tx.audit=6]="audit",Tx[Tx.strategyExtension=7]="strategyExtension",Tx[Tx.standardization=8]="standardization",Tx[Tx.supplier=9]="supplier",Tx[Tx.auditItems=10]="auditItems",(Mx=Ix||(Ix={}))[Mx.currentProgress=1]="currentProgress",Mx[Mx.cumulativeProgress=2]="cumulativeProgress",(Lx=Rx||(Rx={})).uploading="uploading",Lx.waiting="waiting",Lx.done="done",Lx.error="error",Lx.canceled="canceled",Lx.duplicateItem="duplicateItem";const zx={[Sx.waitingStart]:"#D6D6D6",[Sx.running]:"#DAE9F4",[Sx.effectivenessCheck]:"#1B75BB29",[Sx.done]:"#DDEECA",[Sx.suspended]:"#FFF2D6",[Sx.canceled]:"#F4433629"},Fx={[Sx.waitingStart]:"#666666",[Sx.running]:"#1B75BB",[Sx.effectivenessCheck]:"#1B75BB",[Sx.done]:"#4CAF50",[Sx.suspended]:"#FF9800",[Sx.canceled]:"#F44336"},Ux={[Sx.waitingStart]:"waiting-start",[Sx.running]:"running",[Sx.effectivenessCheck]:"effectiveness-check",[Sx.done]:"done",[Sx.suspended]:"suspended",[Sx.canceled]:"canceled"},jx={[Sx.waitingStart]:"Aguardando início",[Sx.running]:"Em andamento",[Sx.effectivenessCheck]:"Verificação de eficácia",[Sx.done]:"Concluída",[Sx.suspended]:"Suspensa",[Sx.canceled]:"Cancelada"},Ox=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}],Bx=[{id:Dx.low,label:"Baixa",color:"#4CAF50"},{id:Dx.medium,label:"Média",color:"#FF9800"},{id:Dx.high,label:"Alta",color:"#F44336"}],$x=[Sx.done,Sx.canceled],Vx=[Sx.waitingStart,Sx.running,Sx.effectivenessCheck,Sx.suspended];function qx(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:s,onDelete:l,onChangeStatus:c}=e,[d,m]=i({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});u(()=>{a&&m(e=>({...e,formData:a,isFormDisabled:r?.disableFields||$x.includes(a.statusId)}))},[a,r?.disableFields]),u(()=>{m(a=>({...a,isLoading:e.isLoading||!1}))},[e.isLoading]);const h=o((e,a)=>{m(t=>({...t,formData:{...t.formData,[e]:a}}))},[]),p=o(e=>{m(a=>({...a,activeTab:e}))},[]),f=o(async()=>{if(n){m(e=>({...e,isSaving:!0}));try{await n(d.formData)}finally{m(e=>({...e,isSaving:!1}))}}},[n,d.formData]),g=o(async e=>{if(c&&d.formData.id){m(e=>({...e,isLoading:!0}));try{await c(d.formData.id,e)}finally{m(e=>({...e,isLoading:!1}))}}},[c,d.formData.id]),v=o(async()=>{if(l&&d.formData.id){m(e=>({...e,isLoading:!0}));try{await l(d.formData.id)}finally{m(e=>({...e,isLoading:!1}))}}},[l,d.formData.id]);return{formData:d.formData,isLoading:d.isLoading,isSaving:d.isSaving,activeTab:d.activeTab,isFormDisabled:d.isFormDisabled,updateField:h,setActiveTab:p,save:f,changeStatus:g,remove:v,cancel:s}}function Wx({status:a,labels:t,className:r}){const n=t?.[a]||jx[a]||"",i=zx[a]||"#D6D6D6",s=Fx[a]||"#666666";return e("span",{className:Ki("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",r),style:{backgroundColor:i,color:s},children:n})}function Hx({formData:t,updateField:r,disabled:i=!1,users:s=[],places:o=[],actionTypes:l,causes:c=[],parentActions:d=[],config:u}){const m=u?.requiredFields,h=l||Ox,p=e=>{if(u?.hiddenFields?.includes(e))return!1;if(u?.visibleFields&&u.visibleFields.length>0)return u.visibleFields.includes(e);const a=`${e}Visible`;return!m||!(a in m)||!1!==m[a]},f=e=>m?!!m[e]:"name"===e,g=n.useMemo(()=>{if(t.startDate&&t.endDate){const e=new Date(t.startDate),a=new Date(t.endDate).getTime()-e.getTime();return Math.max(0,Math.ceil(a/864e5))}return t.duration||0},[t.startDate,t.endDate,t.duration]);return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),e(ts,{value:t.name||"",onChange:e=>r("name",e.target.value),maxLength:500,disabled:i,placeholder:"Nome do plano de ação"})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("responsibleWho")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),a(Ws,{value:t.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o responsável"})}),e(Xs,{children:s.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),p("checkerWho")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),a(Ws,{value:t.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o verificador"})}),e(Xs,{children:s.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("place")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),a(Ws,{value:t.placeId||"",onValueChange:e=>r("placeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o local"})}),e(Xs,{children:Gx(o).map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),p("planType")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),a(Ws,{value:t.typeId||"",onValueChange:e=>r("typeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione o tipo"})}),e(Xs,{children:h.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[p("priority")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),a(Ws,{value:t.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a prioridade"})}),e(Xs,{children:Bx.map(t=>e(Zs,{value:t.id.toString(),children:a("span",{className:"flex items-center gap-2",children:[e("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),d.length>0&&a("div",{className:"space-y-2",children:[e(ns,{children:"Pertence a"}),a(Ws,{value:t.parentId||"",onValueChange:e=>r("parentId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a ação pai"})}),e(Xs,{children:d.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[p("startDate")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),e(Cu,{date:t.startDate?new Date(t.startDate):void 0,onDateChange:e=>r("startDate",e||null),disabled:i,placeholder:"Selecione a data"})]}),p("endDate")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),e(Cu,{date:t.endDate?new Date(t.endDate):void 0,onDateChange:e=>r("endDate",e||null),disabled:i,placeholder:"Selecione a data",disabledDates:t.startDate?e=>e<new Date(t.startDate):void 0})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Duração (dias)"}),e(ts,{type:"number",value:g,disabled:!0,className:"bg-muted"})]})]}),p("estimatedCost")&&a("div",{className:"space-y-2 max-w-xs",children:[e(ns,{className:Ki(f("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),a("div",{className:"relative",children:[e("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),e(ts,{type:"number",min:0,step:.01,value:t.estimatedCost||"",onChange:e=>r("estimatedCost",Number(e.target.value)),disabled:i,className:"pl-9",placeholder:"0,00"})]})]}),p("cause")&&c.length>0&&a("div",{className:"space-y-2",children:[e(ns,{children:"Causa"}),a(Ws,{value:t.causeId||"",onValueChange:e=>r("causeId",e),disabled:i,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a causa"})}),e(Xs,{children:c.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]}),p("description")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),e(to,{value:t.description||"",onChange:e=>r("description",e.target.value),maxLength:4e3,disabled:i,rows:4,placeholder:"Descreva o plano de ação"})]}),p("justification")&&a("div",{className:"space-y-2",children:[e(ns,{className:Ki(f("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),e(to,{value:t.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:i,rows:4,placeholder:"Justificativa do plano de ação"})]})]})}function Gx(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...Gx(r.children,a+1));return t}function Yx(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[s,l]=i(!1),[c,d]=i(null),u=!!a&&Vx.includes(a.status),m=o(async e=>{if(t&&a){l(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{l(!1)}}},[t,a]),h=o(async e=>{if(r){l(!0);try{await r(e)}finally{l(!1),d(null)}}},[r]),p=o(async e=>{if(n){l(!0);try{await n(e)}finally{l(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:s,editingReport:c,setEditingReport:d,reportProgress:m,editProgress:h,deleteProgress:p}}function Kx(e){if(!e)return"";let a=(e||"").trim();if(!a)return"00:00";if(a.includes(":")){const e=a.split(":");if(e.length>=2){const a=e[0].replace(/\D/g,""),t=e[1].replace(/\D/g,"");let r=parseInt(a)||0,n=parseInt(t)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}if(a=a.replace(/\D/g,""),!a)return"00:00";let t=0,r=0;return 4===a.length?(t=parseInt(a.substring(0,2))||0,r=parseInt(a.substring(2,4))||0,t+=Math.floor(r/60),r%=60):(t=parseInt(a)||0,r=0),`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function Qx(e){if(null==e)return"00:00";const a=String(e).replace(/\D/g,"");if(a.length<3){let e=parseInt(a)||0;const t=Math.floor(e/60);return e%=60,`${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=a.slice(-2),t=a.slice(0,-2);let r=parseInt(t)||0,n=parseInt(e)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}function Xx(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Jx({open:t,onOpenChange:r,report:s,onSave:o,isSubmitting:l=!1}){const[c,d]=i(s?.percentProgress||0),[u,m]=i(s?.timeProgress||""),[h,p]=i(s?.comments||""),f=c!==(s?.percentProgress??0)||u!==(s?.timeProgress??"")||h!==(s?.comments??"");n.useEffect(()=>{s&&(d(s.percentProgress),m(s.timeProgress||""),p(s.comments||""))},[s]);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-md",variant:"form",isDirty:f,children:[e(Es,{children:e(Ms,{children:"Editar Progresso"})}),a("div",{className:"space-y-4 py-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Progresso (%)"}),e(ts,{type:"number",min:0,max:100,value:c,onChange:e=>d(Number(e.target.value))})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Tempo gasto (HH:MM)"}),e(ts,{value:u,onChange:e=>m(e.target.value),onBlur:()=>m(Kx(u)||""),placeholder:"00:00"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Comentários"}),e(to,{value:h,onChange:e=>p(e.target.value),rows:3,maxLength:4e3})]})]}),a(Is,{children:[e(es,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),e(es,{onClick:()=>{s&&o({...s,percentProgress:c,timeProgress:Kx(u)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function Zx(t){const{progress:r,canReportProgress:n,isSubmitting:s,editingReport:o,setEditingReport:l,reportProgress:c,editProgress:d,deleteProgress:u}=Yx(t),[m,h]=i(""),[p,f]=i(""),[g,v]=i("");if(!r)return e("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const x=Xx(r.percentProgress),b=!m,y=!m&&!p&&!g;return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[a("div",{className:"flex items-center justify-between text-sm",children:[e("span",{className:"font-medium",children:"Progresso geral"}),a("span",{className:"font-semibold",style:{color:x||void 0},children:[r.percentProgress,"%"]})]}),e(Cm,{value:r.percentProgress,className:"h-3"}),r.timeProgress&&a("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Qx(r.timeProgress)]})]}),n&&a("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e("h4",{className:"text-sm font-medium",children:"Reportar progresso"}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Progresso (%)"}),e(ts,{type:"number",min:0,max:100,value:m,onChange:e=>h(e.target.value),placeholder:"0"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Tempo gasto (HH:MM)"}),e(ts,{value:p,onChange:e=>f(e.target.value),onBlur:()=>f(Kx(p)||""),placeholder:"00:00"})]})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Comentários"}),e(to,{value:g,onChange:e=>v(e.target.value),rows:3,maxLength:4e3,placeholder:"Adicione um comentário sobre o progresso"})]}),a("div",{className:"flex gap-2 justify-end",children:[e(es,{variant:"outline",size:"sm",onClick:()=>{h(""),f(""),v("")},disabled:y||s,children:"Limpar"}),e(es,{size:"sm",onClick:async()=>{const e=Number(m);(e||0===e)&&(await c({percentProgress:e,timeProgress:Kx(p)||"00:00",comments:g}),h(""),f(""),v(""))},disabled:b||s,children:s?"Reportando...":"Reportar"})]})]}),r.reports.length>0&&a("div",{className:"space-y-3",children:[e("h4",{className:"text-sm font-medium",children:"Histórico de reportes"}),e("div",{className:"space-y-2",children:r.reports.map(a=>e(eb,{report:a,onEdit:()=>l(a),onDelete:()=>u(a.id),disabled:!n},a.id))})]}),e(Jx,{open:!!o,onOpenChange:e=>!e&&l(null),report:o,onSave:d,isSubmitting:s})]})}function eb({report:t,onEdit:r,onDelete:n,disabled:i}){const s=t.date?new Date(t.date):null,o=Xx(t.percentProgress);return a("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[e("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[a("div",{className:"flex items-center gap-2 text-sm",children:[e("span",{className:"font-medium truncate",children:t.userName}),s&&e("span",{className:"text-xs text-muted-foreground",children:s.toLocaleDateString("pt-BR")})]}),a("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[a("span",{style:{color:o||void 0},className:"font-semibold",children:[t.percentProgress,"%"]}),t.timeProgress&&a("span",{children:["Tempo: ",Qx(t.timeProgress)]})]}),t.comments&&e("p",{className:"text-xs text-muted-foreground mt-1",children:t.comments})]}),!i&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[e(bo,{onClick:r,children:"Editar"}),e(bo,{className:"text-destructive",onClick:n,children:"Excluir"})]})]})]})}function ab({predecessors:t=[],availablePredecessors:r=[],onAdd:i,onRemove:s,disabled:o=!1}){const[l,c]=n.useState(""),d=r.filter(e=>!t.some(a=>a.predecessorId===e.id));return a("div",{className:"space-y-6 p-1",children:[!o&&d.length>0&&a("div",{className:"flex items-end gap-3",children:[a("div",{className:"flex-1 space-y-2",children:[e(ns,{children:"Adicionar predecessor"}),a(Ws,{value:l,onValueChange:c,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione uma ação"})}),e(Xs,{children:d.map(a=>e(Zs,{value:a.id,children:a.label},a.id))})]})]}),a(es,{size:"sm",onClick:()=>{l&&i&&(i(l),c(""))},disabled:!l,children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),t.length>0?e("div",{className:"space-y-2",children:t.map(t=>a("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[a("div",{className:"flex items-center gap-3",children:[t.predecessorCode&&e("span",{className:"text-xs text-muted-foreground font-mono",children:t.predecessorCode}),e("span",{className:"text-sm font-medium",children:t.predecessorName}),null!=t.predecessorStatus&&e(Wx,{status:t.predecessorStatus})]}),!o&&s&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),e(xo,{align:"end",children:e(bo,{className:"text-destructive",onClick:()=>s(t.predecessorId),children:"Remover"})})]})]},t.id))}):e("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function tb({costs:t=[],onAdd:r,onEdit:n,onDelete:s,disabled:o=!1}){const[l,c]=i(""),[d,u]=i(""),m=t.reduce((e,a)=>e+(a.value||0),0);return a("div",{className:"space-y-6 p-1",children:[a("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[e("span",{className:"text-sm font-medium",children:"Custo total realizado"}),a("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",m.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!o&&r&&a("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[e("h4",{className:"text-sm font-medium",children:"Adicionar custo"}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(ns,{children:"Descrição"}),e(ts,{value:l,onChange:e=>c(e.target.value),placeholder:"Descrição do custo"})]}),a("div",{className:"space-y-2",children:[e(ns,{children:"Valor (R$)"}),e(ts,{type:"number",min:0,step:.01,value:d,onChange:e=>u(e.target.value),placeholder:"0,00"})]})]}),e("div",{className:"flex justify-end",children:a(es,{size:"sm",onClick:()=>{l&&d&&r&&(r({description:l,value:Number(d),date:(new Date).toISOString()}),c(""),u(""))},disabled:!l||!d,children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),t.length>0?e("div",{className:"space-y-2",children:t.map(t=>a("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[a("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:t.description}),t.date&&e("p",{className:"text-xs text-muted-foreground",children:new Date(t.date).toLocaleDateString("pt-BR")})]}),a("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",t.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!o&&(n||s)&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[n&&e(bo,{onClick:()=>n(t),children:"Editar"}),s&&e(bo,{className:"text-destructive",onClick:()=>s(t.id),children:"Excluir"})]})]})]})]},t.id))}):e("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function rb({comments:t=[],currentUserId:r,onAdd:n,onEdit:s,onDelete:o,disabled:l=!1,maxLength:c=4e3}){const[d,u]=i(""),[m,h]=i(!1),[p,f]=i(null),[g,v]=i(""),x=()=>{f(null),v("")};return a("div",{className:"space-y-6 p-1",children:[!l&&n&&a("div",{className:"space-y-3",children:[e(to,{value:d,onChange:e=>u(e.target.value),placeholder:"Adicionar comentário...",maxLength:c,rows:3}),a("div",{className:"flex items-center justify-between",children:[c&&a("span",{className:"text-xs text-muted-foreground",children:[d.length,"/",c]}),a("div",{className:"flex gap-2 ml-auto",children:[e(es,{variant:"outline",size:"sm",onClick:()=>u(""),disabled:!d||m,children:"Limpar"}),e(es,{size:"sm",onClick:async()=>{if(d.trim()&&n){h(!0);try{await n(d),u("")}finally{h(!1)}}},disabled:!d.trim()||m,children:m?"Enviando...":"Comentar"})]})]})]}),a("div",{className:"space-y-1",children:[t.length>0?a("div",{className:"flex items-center gap-2 mb-3",children:[e("span",{className:"text-sm font-medium",children:"Comentários"}),e(no,{variant:"info",className:"text-[10px] px-1.5 py-0",children:t.length})]}):a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(La,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),t.map(t=>a("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[e("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:t.userPhotoUrl?e("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[a("div",{className:"flex items-center gap-2 text-sm",children:[e("span",{className:"font-medium truncate",children:t.userName}),t.userEmail&&e("span",{className:"text-xs text-muted-foreground truncate",children:t.userEmail}),e("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:nb(t.dateEdited||t.dateCreation)}),t.dateEdited&&e("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),p===t.id?a("div",{className:"space-y-2",children:[e(to,{value:g,onChange:e=>v(e.target.value),maxLength:c,rows:3}),a("div",{className:"flex gap-2 justify-end",children:[e(es,{variant:"outline",size:"sm",onClick:x,disabled:m,children:"Cancelar"}),e(es,{size:"sm",onClick:()=>(async e=>{if(g.trim()&&s){h(!0);try{await s({...e,text:g,stringText:g}),f(null),v("")}finally{h(!1)}}})(t),disabled:!g.trim()||m,children:m?"Salvando...":"Salvar"})]})]}):e("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.stringText||t.text})]}),!l&&r===t.userId&&p!==t.id&&a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[s&&e(bo,{onClick:()=>(e=>{f(e.id),v(e.stringText||e.text)})(t),children:"Editar"}),o&&e(bo,{className:"text-destructive",onClick:()=>(async e=>{if(o){h(!0);try{await o(e)}finally{h(!1)}}})(t.id),children:"Excluir"})]})]})]},t.id))]})]})}function nb(e){if(!e)return"";const a=new Date(e);return`${a.toLocaleDateString("pt-BR")} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ib({history:t=[],isLoading:r=!1}){return r?e("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===t.length?a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(Ae,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum registro no histórico"})]}):e("div",{className:"p-1",children:a("div",{className:"relative",children:[e("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),e("div",{className:"space-y-0",children:t.map((t,r)=>a("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[e("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:t.icon?e("span",{className:"text-xs text-primary",children:t.icon}):e("div",{className:"h-2 w-2 rounded-full bg-primary"})}),a("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[a("div",{children:[e("h4",{className:"text-sm font-medium",children:t.translateEvent||t.eventName}),t.eventDescription&&e("p",{className:"text-xs text-muted-foreground",children:t.eventDescription})]}),a("div",{className:"flex items-center gap-2",children:[e("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:t.userPhotoUrl?e("img",{src:t.userPhotoUrl,alt:t.userName,className:"h-full w-full object-cover"}):t.userName?.charAt(0)?.toUpperCase()||"?"}),a("div",{className:"min-w-0",children:[e("span",{className:"text-xs font-medium truncate block",children:t.userName}),t.userEmail&&e("span",{className:"text-[10px] text-muted-foreground truncate block",children:t.userEmail})]})]}),a("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[a("div",{className:"flex items-center gap-1",children:[e(Oe,{className:"h-3 w-3"}),e("span",{children:sb(t.date)})]}),a("div",{className:"flex items-center gap-1",children:[e(Ae,{className:"h-3 w-3"}),e("span",{children:ob(t.date)})]}),t.isMobileRequest&&a("div",{className:"flex items-center gap-1",children:[e(za,{className:"h-3 w-3"}),e("span",{children:"Via app"})]})]})]})]},t.id))})]})})}function sb(e){return new Date(e).toLocaleDateString("pt-BR")}function ob(e){return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function lb({attachments:r=[],onUpload:n,onDelete:s,onRename:o,onDownload:l,onView:c,disabled:u=!1}){const m=d(null),[h,p]=i(null),[f,g]=i(""),v=async e=>{f.trim()&&o&&(await o(e.id,f),p(null),g(""))},x=()=>{p(null),g("")};return a("div",{className:"space-y-4 p-1",children:[!u&&n&&a(t,{children:[e("input",{ref:m,type:"file",multiple:!0,className:"hidden",onChange:e=>{const a=e.target.files;if(a&&n){for(let e=0;e<a.length;e++){const t=a.item(e);t&&n(t)}m.current&&(m.current.value="")}}}),a(es,{size:"sm",onClick:()=>m.current?.click(),children:[e(Y,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),r.length>0?e("div",{className:"space-y-2",children:r.map(r=>a("div",{className:Ki("flex items-center gap-3 rounded-lg border bg-card p-3",r.status===Rx.error&&"border-destructive/50 bg-destructive/5",r.status===Rx.canceled&&"opacity-50"),children:[e("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:e("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:r.extension.replace(".","").substring(0,4)})}),a("div",{className:"flex-1 min-w-0 space-y-1",children:[h===r.id?a("div",{className:"flex items-center gap-2",children:[e("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:f,onChange:e=>g(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v(r),"Escape"===e.key&&x()},autoFocus:!0}),e(es,{size:"sm",variant:"outline",onClick:x,children:"Cancelar"}),e(es,{size:"sm",onClick:()=>v(r),children:"Salvar"})]}):e("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>c?.(r.id),children:r.name}),(r.status===Rx.uploading||r.status===Rx.waiting)&&e(Cm,{value:r.progress||0,className:"h-1.5"}),r.status===Rx.error&&e("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),r.status===Rx.duplicateItem&&e("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),r.status===Rx.canceled&&e("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),a("div",{className:"flex items-center gap-2",children:[r.status===Rx.done&&a(t,{children:[e("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:cb(r.size)}),a(co,{children:[e(uo,{asChild:!0,children:e(as,{})}),a(xo,{align:"end",children:[o&&!u&&e(bo,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");p(e.id),g(a)})(r),children:"Renomear"}),c&&e(bo,{onClick:()=>c(r.id),children:"Visualizar"}),l&&e(bo,{onClick:()=>l(r.id),children:"Download"}),s&&!u&&a(t,{children:[e(Co,{}),e(bo,{className:"text-destructive",onClick:()=>s(r.id),children:"Excluir"})]})]})]})]}),r.status===Rx.uploading&&e(es,{variant:"outline",size:"sm",onClick:()=>s?.(r.id),children:"Cancelar"})]})]},r.id))}):a("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e(Fa,{className:"h-8 w-8 mb-2 opacity-50"}),e("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function cb(e){if(0===e)return"0 B";const a=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,a)).toFixed(1))} ${["B","KB","MB","GB"][a]}`}function db(t){const{formData:r,isLoading:n,isSaving:i,activeTab:s,isFormDisabled:o,updateField:l,setActiveTab:c,save:d,changeStatus:u,remove:m,cancel:h}=qx(t),{isNew:p=!1,config:f,users:g,places:v,actionTypes:x,causes:b,parentActions:y,progress:N,predecessors:w,availablePredecessors:C,costs:k,comments:_,history:S,attachments:A,attachmentsSlot:D,commentsSlot:P,historySlot:E,onAddPredecessor:T,onRemovePredecessor:I,onAddCost:M,onEditCost:R,onDeleteCost:L,onAddComment:z,onEditComment:F,onDeleteComment:U,onUploadAttachment:j,onDeleteAttachment:O,onRenameAttachment:B,onDownloadAttachment:$,onViewAttachment:V}=t;if(n&&!r.id)return e(oo,{isLoading:!0,children:e("div",{})});const q=function(e){if(!e)return[];return{[Sx.waitingStart]:[Sx.running,Sx.suspended,Sx.canceled],[Sx.running]:[Sx.effectivenessCheck,Sx.done,Sx.suspended,Sx.canceled],[Sx.effectivenessCheck]:[Sx.running,Sx.done,Sx.suspended,Sx.canceled],[Sx.done]:[Sx.running],[Sx.suspended]:[Sx.running,Sx.canceled],[Sx.canceled]:[Sx.waitingStart]}[e]||[]}(r.statusId);return a("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[a("div",{className:"flex items-center gap-4",children:[h&&e(es,{variant:"ghost",size:"icon",onClick:h,children:e(Pe,{className:"h-4 w-4"})}),a("div",{className:"space-y-1",children:[a("div",{className:"flex items-center gap-3",children:[e("h1",{className:"text-lg font-semibold",children:p?"Nova Ação":r.name||"Plano de Ação"}),!p&&r.statusId&&e(Wx,{status:r.statusId})]}),r.code&&e("p",{className:"text-xs text-muted-foreground font-mono",children:r.code})]})]}),a("div",{className:"flex items-center gap-2",children:[!p&&q.length>0&&!o&&a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"outline",size:"sm",children:"Alterar Status"})}),e(xo,{align:"end",children:q.map(a=>e(bo,{onClick:()=>u(a),children:jx[a]},a))})]}),!p&&t.onDelete&&a(co,{children:[e(uo,{asChild:!0,children:e(es,{variant:"ghost",size:"icon",children:e(Ea,{className:"h-4 w-4"})})}),e(xo,{align:"end",children:e(bo,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),e("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e("div",{className:"max-w-4xl mx-auto px-6 py-6",children:a(Fd,{value:s,onValueChange:c,children:[a(Ud,{className:"mb-6",children:[e(jd,{value:"general",children:"Geral"}),!p&&e(jd,{value:"progress",children:"Progresso"}),!p&&f?.enablePredecessors&&e(jd,{value:"predecessors",children:"Predecessores"}),!p&&f?.enableCosts&&e(jd,{value:"costs",children:"Custos"}),!p&&f?.enableAttachments&&e(jd,{value:"attachments",children:"Anexos"}),!p&&f?.enableComments&&e(jd,{value:"comments",children:"Comentários"}),!p&&f?.enableHistory&&e(jd,{value:"history",children:"Histórico"})]}),e(Od,{value:"general",children:e(Hx,{formData:r,updateField:l,disabled:o,users:g,places:v,actionTypes:x,causes:b,parentActions:y,config:f})}),!p&&e(Od,{value:"progress",children:e(Zx,{...t})}),!p&&f?.enablePredecessors&&e(Od,{value:"predecessors",children:e(ab,{predecessors:w,availablePredecessors:C,onAdd:T,onRemove:I,disabled:o})}),!p&&f?.enableCosts&&e(Od,{value:"costs",children:e(tb,{costs:k,onAdd:M,onEdit:R,onDelete:L,disabled:o})}),!p&&f?.enableAttachments&&e(Od,{value:"attachments",children:D||e(lb,{attachments:A,onUpload:j,onDelete:O,onRename:B,onDownload:$,onView:V,disabled:o})}),!p&&f?.enableComments&&e(Od,{value:"comments",children:P||e(rb,{comments:_,onAdd:z,onEdit:F,onDelete:U,disabled:o})}),!p&&f?.enableHistory&&e(Od,{value:"history",children:E||e(ib,{history:S})})]})})}),a("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[h&&e(es,{variant:"outline",onClick:h,disabled:i,children:"Cancelar"}),e(es,{onClick:d,disabled:i||o,children:i?"Salvando...":"Salvar"})]})]})}const ub=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function mb(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const a=e/1024;if(a<1024)return`${Math.round(a)} KB`;const t=a/1024;if(t<1024)return`${Math.round(t)} MB`;const r=t/1024;return Math.round(100*r)/100+" GB"}function hb(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function pb({storedFile:t,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:s,minSizeInBytes:l=1,maxSizeInBytes:c=314572800,showDownloadButton:u=!0,showViewButton:m=!0,showReplaceButton:h=!0,showCloseButton:p=!0,required:f=!1,touched:g=!1,disabled:v=!1,error:x,onFileSelect:b,onFileRemove:y,onFileReplace:N,onDownload:w,onView:C,className:k}){const _=d(null),[A,D]=i(null),[P,E]=i(null),[T,I]=i(!1),M=A||t,R=A?.name||t?.name||"",L=A?.size||t?.size;R&&hb(R);const z=r||R,F=u&&!A&&!!t,U=m&&!A&&!!t,j=!!P||!!x||f&&g&&!M,O=!!M,B=o(e=>{if(ub.includes(e.type))return{type:"forbidden-type"};if(e.size<=l)return{type:"min-size"};if(e.size>=c)return{type:"max-size"};if(n?.length){const a=hb(e.name);if(!n.includes(a))return{type:"extension",message:s}}return null},[l,c,n,s]),$=o(e=>{const a=e.target.files?.[0];if(!a)return;const t=B(a);if(t)return E(t),D(null),void(_.current&&(_.current.value=""));E(null),D(a),b?.(a),_.current&&(_.current.value="")},[B,b]),V=o(e=>{if(e.preventDefault(),e.stopPropagation(),v)return;const a=e.dataTransfer.files?.[0];if(!a)return;const t=B(a);if(t)return E(t),void D(null);E(null),D(a),b?.(a)},[v,B,b]),q=o(e=>{e.preventDefault(),e.stopPropagation()},[]),W=o(()=>{N?.(),_.current?.click()},[N]),H=o(()=>{D(null),E(null),y?.(),_.current&&(_.current.value="")},[y]),G=o(async()=>{if(!T&&t&&w){I(!0);try{await w(t)}finally{I(!1)}}},[T,t,w]),Y=o(()=>{t&&C&&C(t)},[t,C]),K=o(()=>{v||_.current?.click()},[v]),Q=(()=>{if(x)return x;if(!P)return f&&g&&!M?"Campo obrigatório":null;switch(P.type){case"extension":return P.message||"Extensão de arquivo não permitida";case"forbidden-type":return"Tipo de arquivo não permitido";case"min-size":return`Tamanho mínimo: ${mb(l)}`;case"max-size":return`Tamanho máximo: ${mb(c)}`;default:return"Erro no arquivo"}})();return a("div",{className:Ki("space-y-1",k),children:[e("div",{className:Ki("rounded-md border border-dashed transition-colors",O&&"border-solid border-border",!O&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",j&&"border-destructive border-solid",v&&"opacity-50 pointer-events-none"),children:a("div",O?{className:"flex items-center justify-between px-3 min-h-[36px]",children:[a("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e(xe,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e("p",{className:"text-xs truncate",children:z})]}),a("div",{className:"flex items-center gap-2 shrink-0",children:[null!=L&&e("span",{className:"text-xs text-muted-foreground",children:mb(L)}),a("div",{className:"flex items-center gap-0.5",children:[F&&w&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:G,children:e(Ce,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Download"})]}),U&&C&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:e(me,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Visualizar"})]}),h&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:W,children:e(Je,{className:"h-3.5 w-3.5 text-primary"})})}),e(Do,{children:"Substituir"})]}),p&&a(So,{children:[e(Ao,{asChild:!0,children:e(es,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:H,children:e(S,{className:"h-3 w-3 text-muted-foreground"})})}),e(Do,{children:"Remover"})]})]})]})]}:{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:K,onKeyDown:e=>"Enter"===e.key&&K(),onDrop:V,onDragOver:q,children:[e(Ua,{className:"h-4 w-4 text-muted-foreground"}),a("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",e("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),Q&&e("p",{className:"text-xs text-destructive",children:Q}),e("input",{ref:_,type:"file",className:"hidden",accept:n?.map(e=>`.${e}`).join(","),onChange:$,disabled:v})]})}var fb,gb,vb,xb,bb,yb;function Nb(e){switch(e.type){case fb.text:return e.textValue;case fb.number:return e.numberValue;case fb.date:return e.dateValue;case fb.time:return e.timeValue;case fb.url:case fb.singleSelection:case fb.multiSelection:return e.itemsValue;case fb.questions:return e.questionsValue;case fb.readOnlyText:return e.textValue;default:return null}}function wb(e,a){if(!a)return!0;const t=null!=Nb(e)&&""!==Nb(e)&&!(Array.isArray(Nb(e))&&0===Nb(e).length);return!1!==e.isActive||t}function Cb(e){return e.filter(e=>e.type!==fb.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===fb.text?e.textValue:void 0,numberValue:e.type===fb.number?e.numberValue:void 0,dateValue:e.type===fb.date?e.dateValue:void 0,timeValue:e.type===fb.time?e.timeValue:void 0,itemsValue:[fb.url,fb.singleSelection,fb.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===fb.questions?e.questionsValue:void 0}))}function kb(e,a){return a?.length?e.map(e=>{const t=a.find(a=>a.formFieldAssociationId===e.id);if(!t)return e;const r={...e};switch(e.type){case fb.text:r.textValue=t.textValue;break;case fb.number:r.numberValue=t.numberValue;break;case fb.date:r.dateValue=t.dateValue;break;case fb.time:r.timeValue=t.timeValue;break;case fb.url:case fb.singleSelection:case fb.multiSelection:r.itemsValue=t.itemsValue||[];break;case fb.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function _b(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===fb.readOnlyText)return;const t=Nb(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===fb.number&&null!=t){const r=e.config;null!=r?.min&&t<r.min&&a.push(e.id),null!=r?.max&&t>r.max&&a.push(e.id)}}),{valid:0===a.length,invalidFields:[...new Set(a)]}}function Sb({field:t}){return a("div",{className:"space-y-1",children:[t.name&&e("p",{className:"text-sm font-medium text-foreground",children:t.name}),t.description&&e("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:t.description}),t.textValue&&e("p",{className:"text-sm text-muted-foreground italic",children:t.textValue})]})}function Ab({field:t,readOnly:r,onChange:n}){const i=t.config,s=i?.multiline??!1,o=r||t.readOnly,l=e=>{n?.({...t,textValue:e})};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),s?e(to,{value:t.textValue||"",onChange:e=>l(e.target.value),placeholder:t.placeholder,disabled:o,rows:4}):e(ts,{value:t.textValue||"",onChange:e=>l(e.target.value),placeholder:t.placeholder,disabled:o})]})}function Db({field:t,readOnly:r,onChange:n}){const i=r||t.readOnly,s=t.dateValue?"string"==typeof t.dateValue?t.dateValue.substring(0,10):new Date(t.dateValue).toISOString().substring(0,10):"";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"date",value:s,onChange:e=>{return a=e.target.value,void n?.({...t,dateValue:a||void 0});var a},placeholder:t.placeholder,disabled:i})]})}function Pb({field:t,readOnly:r,onChange:n}){const i=r||t.readOnly,s=e=>{if(!e)return;const[a,t]=e.split(":").map(Number);return 60*a+t};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"time",value:(e=>{if(null==e)return"";const a=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`})(t.timeValue),onChange:e=>n?.({...t,timeValue:s(e.target.value)}),placeholder:t.placeholder,disabled:i})]})}function Eb({field:t,readOnly:r,onChange:n}){const s=t.config,o=s?.multiple??!1,l=r||t.readOnly,[c,d]=i(""),u=t.itemsValue||[],m=()=>{if(!c.trim())return;const e={value:crypto.randomUUID(),text:c.trim()};n?.({...t,itemsValue:[...u,e]}),d("")};if(!o){const r=u[0]?.text||"";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),a("div",{className:"flex items-center gap-2",children:[e(ts,{type:"url",value:r,onChange:e=>(e=>{const a={value:e,text:e};n?.({...t,itemsValue:e?[a]:[]})})(e.target.value),placeholder:t.placeholder||"https://",disabled:l}),r&&e(es,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:e("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:e(Ze,{className:"h-4 w-4"})})})]})]})}return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),!l&&a("div",{className:"flex items-center gap-2",children:[e(ts,{type:"url",value:c,onChange:e=>d(e.target.value),placeholder:t.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),e(es,{variant:"outline",size:"icon",onClick:m,disabled:!c.trim(),className:"flex-shrink-0",children:e(Y,{className:"h-4 w-4"})})]}),u.length>0&&e("div",{className:"space-y-1",children:u.map((r,i)=>a("div",{className:"flex items-center gap-2 text-sm",children:[e("a",{href:r.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:r.text}),!l&&e(es,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(e=>{const a=u.filter((a,t)=>t!==e);n?.({...t,itemsValue:a})})(i),children:e(q,{className:"h-3 w-3"})})]},r.value))})]})}function Tb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e(ts,{type:"number",value:t.numberValue??"",onChange:e=>(e=>{if(""===e)return void n?.({...t,numberValue:void 0});const a=parseFloat(e);isNaN(a)||n?.({...t,numberValue:a})})(e.target.value),placeholder:t.placeholder,disabled:s,min:i?.min,max:i?.max,step:o}),null!=i?.min&&null!=i?.max&&a("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function Ib({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.viewMode??vb.dropdown,l=i?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(a=>a.value===e.value))||[],c=t.itemsValue?.[0]?.value||"",d=e=>{const a=l.find(a=>a.value===e);if(!a)return;const r={value:a.value,text:a.text,isActive:a.isActive};n?.({...t,itemsValue:[r]})};return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),o===vb.dropdown&&a(Ws,{value:c,onValueChange:d,disabled:s,children:[e(Ys,{children:e(Gs,{placeholder:t.placeholder||"Selecione..."})}),e(Xs,{children:l.map(t=>a(Zs,{value:t.value,children:[t.text,!1===t.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},t.value))})]}),(o===vb.radio||o===vb.buttons)&&e(km,{value:c,onValueChange:d,disabled:s,className:Ki(o===vb.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>a("div",{className:"flex items-center gap-2",children:[e(_m,{value:r.value,id:`${t.id}-${r.value}`}),a(ns,{htmlFor:`${t.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))}),!s&&c&&!t.required&&e("button",{type:"button",onClick:()=>{n?.({...t,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function Mb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.viewMode??vb.dropdown,l=i?.data?.filter(e=>!1!==e.isActive||t.itemsValue?.some(a=>a.value===e.value))||[],c=new Set(t.itemsValue?.map(e=>e.value)||[]);return a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),(t.itemsValue?.length??0)>0&&e("div",{className:"flex flex-wrap gap-1.5",children:t.itemsValue.map(r=>a(no,{variant:"secondary",className:"gap-1 pr-1",children:[e("span",{className:"text-xs",children:r.text}),!s&&e("button",{type:"button",onClick:()=>(e=>{const a=(t.itemsValue||[]).filter(a=>a.value!==e);n?.({...t,itemsValue:a})})(r.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:e(S,{className:"h-3 w-3"})})]},r.value))}),!s&&e("div",{className:Ki(o===vb.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:l.map(r=>a("div",{className:"flex items-center gap-2",children:[e(ao,{id:`${t.id}-${r.value}`,checked:c.has(r.value),onCheckedChange:()=>(e=>{const a=t.itemsValue||[],r=a.some(a=>a.value===e.value)?a.filter(a=>a.value!==e.value):[...a,{value:e.value,text:e.text,isActive:e.isActive}];n?.({...t,itemsValue:r})})(r),disabled:s}),a(ns,{htmlFor:`${t.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&e("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))})]})}function Rb({field:t,readOnly:r,onChange:n}){const i=t.config,s=r||t.readOnly,o=i?.questions||[],l=i?.options||[],c=t.questionsValue||[];return 0===o.length||0===l.length?a("div",{className:"space-y-1.5",children:[e(ns,{children:t.name}),e("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):a("div",{className:"space-y-1.5",children:[e(ns,{className:Ki(t.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:t.name}),t.description&&e("p",{className:"text-xs text-muted-foreground",children:t.description}),e("div",{className:"border rounded-md overflow-x-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{children:a("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),l.map(a=>e("th",{className:"text-center p-2 font-medium min-w-[80px]",children:a.text},a.value))]})}),e("tbody",{children:o.map((r,i)=>a("tr",{className:Ki(i<o.length-1&&"border-b"),children:[e("td",{className:"p-2 text-muted-foreground",children:r.text}),l.map(a=>{return e("td",{className:"text-center p-2",children:e(km,{value:(i=r.value,c.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:e=>((e,a,r,i)=>{const s={questionValue:e,questionText:a,optionValue:r,optionText:i},o=c.filter(a=>a.questionValue!==e);o.push(s),n?.({...t,questionsValue:o})})(r.value,r.text,e,a.text),disabled:s,className:"flex justify-center",children:e(_m,{value:a.value,id:`${t.id}-${r.value}-${a.value}`})})},a.value);var i})]},r.value))})]})})]})}function Lb({fields:a,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const s=o(e=>{if(i?.(e),n){const t=a.map(a=>a.id===e.id?e:a);n(t)}},[a,n,i]),l=a.filter(e=>wb(e,r));return 0===l.length?null:e("div",{className:"space-y-4",children:l.map(a=>e(zb,{field:a,readOnly:t,onChange:s},a.id))})}function zb({field:a,readOnly:t,onChange:r}){const n={field:a,readOnly:t,onChange:r};switch(a.type){case fb.readOnlyText:return e(Sb,{...n});case fb.text:return e(Ab,{...n});case fb.date:return e(Db,{...n});case fb.time:return e(Pb,{...n});case fb.url:return e(Eb,{...n});case fb.number:return e(Tb,{...n});case fb.singleSelection:return e(Ib,{...n});case fb.multiSelection:return e(Mb,{...n});case fb.questions:return e(Rb,{...n});default:return null}}function Fb({queryParams:t,events:r,softwares:n,users:s=[],permissions:l={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:c=!1,onFilter:d,onReset:u,onExport:m,onSoftwareChange:h}){const[p,f]=i(t.softwareId),[g,v]=i(t.eventId),[x,b]=i(t.userId||"all"),[y,N]=i(Ub(t.startDate)),[w,C]=i(Ub(t.endDate)),k=o(e=>{const a=parseInt(e);f(a),h?.(a)},[h]),_=o(()=>{d({...t,softwareId:p,eventId:g,userId:"all"===x?void 0:x,startDate:new Date(y),endDate:new Date(w),software:n.find(e=>e.id===p)?.software||t.software,event:r.find(e=>e.id===g)?.name||t.event})},[t,p,g,x,y,w,n,r,d]),S=o(()=>{const e=new Date;e.setHours(0,0,0,0),N(Ub(e)),C(Ub(e)),v(t.eventId),l.viewAllEvents&&b("all"),u?.()},[t.eventId,l.viewAllEvents,u]),A=l.viewOnlyMyEvents&&!l.viewAllEvents,D=p&&g&&y&&w;return a("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[a("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Módulo *"}),a(Ws,{value:String(p),onValueChange:k,disabled:c,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),e(Xs,{children:n.map(a=>e(Zs,{value:String(a.id),className:"text-xs",children:a.translation},a.id))})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Evento *"}),a(Ws,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:c,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),e(Xs,{children:r.map(a=>e(Zs,{value:String(a.id),className:"text-xs",children:a.translation},a.id))})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Usuário *"}),a(Ws,{value:x,onValueChange:b,disabled:c||A,children:[e(Ys,{className:"h-8 text-xs",children:e(Gs,{placeholder:"Selecione..."})}),a(Xs,{children:[e(Zs,{value:"all",className:"text-xs",children:"Todos"}),s.map(a=>e(Zs,{value:a.id,className:"text-xs",children:a.name},a.id))]})]})]}),a("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"De *"}),e(ts,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",max:w,disabled:c})]}),a("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[e(ns,{className:"text-xs text-muted-foreground",children:"Até *"}),e(ts,{type:"date",value:w,onChange:e=>C(e.target.value),className:"h-8 text-xs",min:y,disabled:c})]}),a("div",{className:"flex items-center gap-2 ml-auto",children:[a(es,{variant:"outline",size:"sm",onClick:S,disabled:c,children:[e(ja,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),l.download&&m&&a(es,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:c,children:[e(Ce,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),a(es,{size:"sm",onClick:_,disabled:c||!D,children:[e(Ie,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Ub(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function jb(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:Bb(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Ob(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Ob(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function Bb(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function $b(e,a){const t=[],r={...Kb,...a?.labels},n=e.eventName;t.push({name:r.event,value:n});const i=e.entities?.[0];if(i&&(t.push({name:r.entityName,value:Vb(i)}),i.description&&t.push({name:r.description,value:i.description}),i.justification&&t.push({name:r.justification,value:i.justification}),i.statusName&&t.push({name:r.status,value:i.statusName}),i.equipmentType&&t.push({name:r.type,value:i.equipmentType}),i.extra?.length)){[...new Set(i.extra.map(e=>e.property))].forEach(e=>{const a=i.extra.filter(a=>a.property===e).map(e=>e.value||"").join(", ");t.push({name:Gb(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=qb(e,n,a?.translateProperty),s=Wb(e,null,n,r,a);s&&t.push({name:i,value:s})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Vb(e);return`(${e.softwareName||e.type}) ${a}`});a.length&&t.push({name:r.references,value:a.join(", ")})}}),i?.isElectronicSigned&&t.push({name:r.security,value:"🛡️ "+r.electronicSigned}),t.push({name:r.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const s=a?.formatDate?a.formatDate(e.dateTime):Yb(e.dateTime);return t.push({name:r.accomplishedIn,value:s}),t}function Vb(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function qb(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=Gb(e.property);return t?t(a,r):r}function Wb(e,a,t,r,n){if(e.propertyResource||(e.propertyResource=a?`${a.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const a=qb(e,t,n?.translateProperty),i=function(e,a){switch(e.state){case"Added":return a.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?a.stateRemoved:a.stateModified;default:return""}}(e,r);let s=`${a}: "${Hb(e,"newValue",r,n)}" ${i}`;const o=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Wb(a,e,t,r,n)));return o.some(Boolean)&&(s+="\n"+o.filter(Boolean).join("\n")),s}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Wb(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=Hb(e,"oldValue",r,n),s=Hb(e,"newValue",r,n);return`${a?qb(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${s}"`}const i=Hb(e,"newValue",r,n);return a?`${qb(e,t,n?.translateProperty)}: ${i}`:i}function Hb(e,a,t,r){const n=e[a];return null==n||""===n?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?t.uninformed:"":"string"==typeof n&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const a=new Date(e);return!isNaN(a.getTime())}(n)?r?.formatDate?r.formatDate(n):Yb(n):String(n)}function Gb(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function Yb(e){try{return new Date(e).toLocaleString()}catch{return e}}(gb=fb||(fb={}))[gb.readOnlyText=1]="readOnlyText",gb[gb.text=2]="text",gb[gb.date=3]="date",gb[gb.time=4]="time",gb[gb.url=5]="url",gb[gb.number=6]="number",gb[gb.singleSelection=7]="singleSelection",gb[gb.multiSelection=8]="multiSelection",gb[gb.questions=9]="questions",(xb=vb||(vb={}))[xb.dropdown=1]="dropdown",xb[xb.buttons=2]="buttons",xb[xb.radio=3]="radio",xb[xb.checkbox=4]="checkbox",(yb=bb||(bb={}))[yb.custom=1]="custom",yb[yb.users=2]="users",yb[yb.usersLists=3]="usersLists";const Kb={event:"Evento",entityName:"Item",description:"Descrição",justification:"Justificativa",status:"Status",type:"Tipo",references:"Referências",security:"Segurança",electronicSigned:"Assinatura Eletrônica",accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:"Não informado",stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Qb({documentId:t,onFetchDetails:r,onClose:n,labels:s,translateProperty:l,translatePropertyValue:c,formatDate:d}){const[m,h]=i(!1),[p,f]=i([]),[g,v]=i(null),x=o(async e=>{h(!0),v(null);try{const a=$b(await r(e),{translateProperty:l,translatePropertyValue:c,formatDate:d,labels:s});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{h(!1)}},[r,l,c,d,s]);return u(()=>{t&&x(t)},[t,x]),t?a("div",{className:"flex flex-col h-full bg-background",children:[a("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[e("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),e(es,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:e(S,{className:"h-4 w-4"})})]}),e("div",{className:"flex-1 overflow-y-auto",children:m?a("div",{className:"flex items-center justify-center p-6",children:[e(so,{size:"md"}),e("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):g?e("div",{className:"p-6 text-sm text-destructive",children:g}):e("table",{className:"w-full text-xs",children:e("tbody",{children:p.map((t,r)=>a("tr",{className:r%2==0?"bg-background":"bg-muted/20",children:[e("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:t.name}),e("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:e("span",{dangerouslySetInnerHTML:{__html:t.value.replace(/\n/g,"<br />")}})})]},r))})})})]}):null}function Xb({title:t="Trilha de Auditoria",softwares:r,softwareId:n,permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:l,limit:c=2e3,currentUserId:m,labels:h,formatDate:p,anonymousLabel:f="Anônimo"}){const[g,v]=i(!0),[x,b]=i([]),[y,N]=i([]),[w,C]=i([]),[k,_]=i(null),[S,A]=i(!1),D=d(null),P=new Date;P.setHours(0,0,0,0);const[E,T]=i({software:r.find(e=>e.id===n)?.software||"",softwareId:n,event:"All",eventId:1,startDate:P,endDate:P,limit:c,softwares:r,userId:s.viewOnlyMyEvents&&!s.viewAllEvents?m:void 0});u(()=>{(async()=>{v(!0);try{const[e,a]=await Promise.all([l.onFetchEvents(E.softwareId),l.onFetchUsers?.()??Promise.resolve([])]);N(e),C(a),await I(E,e)}catch(e){}finally{v(!1)}})()},[]);const I=o(async(e,a)=>{try{const t=jb((await l.onFetchTrails(e)).data,a||y,r,f);b(t)}catch(t){}},[l,y,r,f]),M=o(async e=>{v(!0),T(e);try{await I(e)}finally{v(!1)}},[I]),R=o(async e=>{try{const a=await l.onFetchEvents(e);N(a)}catch(a){}},[l]),L=o(e=>{_(e.documentId),A(!0)},[]),z=o(()=>{A(!1),_(null)},[]),F=o(async()=>{const e={...E,startDate:P,endDate:P,eventId:1,userId:s.viewAllEvents?void 0:m};T(e),v(!0);try{await I(e)}finally{v(!1)}},[E,I]),U=o(e=>{l.onExport?.(e,x)},[l,x]),j=o(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return a("div",{className:"flex flex-col h-full",children:[e("div",{className:"p-3",children:e(Fb,{queryParams:E,events:y,softwares:r,users:w,permissions:s,isLoading:g,onFilter:M,onReset:F,onExport:s.download?U:void 0,onSoftwareChange:R})}),a("div",{className:"flex flex-1 min-h-0 relative",children:[a("div",{className:Ki("flex-1 overflow-auto transition-all duration-300",S?"mr-[400px]":""),children:[g?a("div",{className:"flex items-center justify-center h-64",children:[e(so,{size:"md"}),e("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===x.length?a("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e(xe,{className:"h-12 w-12 mb-3 opacity-30"}),e("p",{className:"text-sm",children:"Nenhum registro encontrado"}),e("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):a("table",{className:"w-full text-xs border-collapse",children:[e("thead",{className:"sticky top-0 z-10",children:a("tr",{className:"bg-muted/60 border-b border-border",children:[e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(Oa,{className:"h-3 w-3"}),"Módulo"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(Ae,{className:"h-3 w-3"}),"Data"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(qe,{className:"h-3 w-3"}),"Usuário"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:a("div",{className:"flex items-center gap-1.5",children:[e(xe,{className:"h-3 w-3"}),"Evento"]})}),e("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),e("th",{className:"px-3 py-2 w-10"})]})}),e("tbody",{children:x.map((t,r)=>a("tr",{onClick:()=>L(t),className:Ki("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",k===t.documentId&&"bg-accent",r%2==0?"bg-background":"bg-muted/10"),children:[e("td",{className:"px-3 py-2 text-foreground",children:t.translatedSoftware}),e("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:t.date?j(t.date.toISOString()):"—"}),e("td",{className:"px-3 py-2 text-foreground",children:t.user}),e("td",{className:"px-3 py-2 text-foreground",children:t.translatedEvent}),e("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:t.entityName,children:t.entityName}),e("td",{className:"px-3 py-2",children:e(me,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},t.documentId||r))})]}),!g&&x.length>0&&a("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[x.length," registro",1!==x.length?"s":""]})]}),e("div",{ref:D,className:Ki("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",S?"translate-x-0":"translate-x-full"),children:S&&e(Qb,{documentId:k,onFetchDetails:l.onFetchDetails,onClose:z,labels:h,translateProperty:l.translateProperty,translatePropertyValue:l.translatePropertyValue,formatDate:p||j})})]})]})}function Jb({open:t,onOpenChange:r,returnSteps:n,initialObservation:s="",title:o="Executar ação",descriptions:l=[],setDefaultApproverOnInit:c=!0,onSubmit:d}){const[u,m]=i(!0),[h,p]=i(c&&n.length>0?n[0].id:null),[f,g]=i(s),v=e=>{m(e),e&&!c?p(null):!e&&!c&&n.length>0&&p(n[0].id)},x=f!==s||!u;return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-[480px]",variant:"form",isDirty:x,children:[e(Es,{children:e(Ms,{children:o})}),a("div",{className:"space-y-4",children:[l.length>0&&e("div",{className:"space-y-1 text-sm text-muted-foreground",children:l.map((a,t)=>e("p",{dangerouslySetInnerHTML:{__html:a}},t))}),a("div",{className:"flex gap-4",children:[a("label",{className:"flex items-center gap-2 cursor-pointer",children:[e("input",{type:"radio",name:"approved",checked:u,onChange:()=>v(!0),className:"accent-primary"}),e("span",{className:"text-sm",children:"Aprovar"})]}),a("label",{className:"flex items-center gap-2 cursor-pointer",children:[e("input",{type:"radio",name:"approved",checked:!u,onChange:()=>v(!1),className:"accent-primary"}),e("span",{className:"text-sm",children:"Reprovar e retornar para etapa"})]})]}),a("div",{className:"space-y-1.5",children:[e(ns,{children:"Etapa"}),a(Ws,{value:h??void 0,onValueChange:p,disabled:u,children:[e(Ys,{children:e(Gs,{placeholder:"Selecione a etapa"})}),e(Xs,{children:n.map(a=>e(Zs,{value:a.id,children:a.name},a.id))})]})]}),a("div",{className:"space-y-1.5",children:[e(ns,{children:"Parecer *"}),e(to,{value:f,onChange:e=>g(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),a("p",{className:"text-xs text-muted-foreground text-right",children:[f.length,"/",4e3]})]})]}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),e(es,{onClick:()=>{if(!f.trim())return void C.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=u?null:n.find(e=>e.id===h);d({approved:u,returnStepId:u?null:h,returnType:e?.type??null,observation:f})},disabled:!x,children:"Concluir"})]})]})})}function Zb({open:t,onOpenChange:r,approvers:n,isLoading:o=!1,ignoreUserIds:l=[],onSubmit:c}){const[d,u]=i(null),m=s(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=s(()=>m.map(e=>({value:e.id,label:e.name})),[m]);return e(Cs,{open:t,onOpenChange:r,children:a(Ps,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!d,children:[e(Es,{children:e(Ms,{children:"Selecionar aprovador"})}),e(oo,{isLoading:o,type:"spinner",children:e("div",{className:"space-y-4",children:e(Wo,{options:h,value:d??void 0,onValueChange:e=>u("string"==typeof e?e:e?.[0]??null),placeholder:"Selecione um aprovador...",searchPlaceholder:"Buscar aprovador..."})})}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),e(es,{onClick:()=>{if(!d)return;const e=m.find(e=>e.id===d);e&&c(e)},disabled:!d||o,children:"Concluir"})]})]})})}function ey(e){if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function ay({text:t,maxLength:r=130}){const[n,s]=i(!1);return t.length<=r?e("span",{children:t}):a("span",{children:[n?t:`${t.substring(0,r)}... `,e("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>s(!n),children:n?"Ler menos":"Ler mais"})]})}function ty({approver:t}){if(1===t.type&&t.approverId)return a(cu,{className:"h-9 w-9 shrink-0",children:[e(du,{src:t.photoUrl,alt:t.name}),e(uu,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]});const r=2===t.type?Sa:3===t.type?je:qe;return e("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:e(r,{className:"h-4 w-4 text-background"})})}function ry({approver:t}){return t.date?a("div",{className:"flex items-center gap-2 flex-wrap",children:[a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[e(Qe,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),e("span",{className:"text-xs text-muted-foreground",children:ey(t.date)}),1!==t.type&&t.approvedUsername&&a("span",{className:"text-xs text-muted-foreground",children:["por ",t.approvedUsername]})]}):t.returnDate?a("div",{className:"flex items-center gap-2 flex-wrap",children:[a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[e(Ba,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),e("span",{className:"text-xs text-muted-foreground",children:ey(t.returnDate)})]}):a("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[e(U,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function ny({approver:t}){const r=1!==t.type||t.approverId?t.name:"A definir";return a("div",{children:[2===t.type&&e("p",{className:"text-xs text-muted-foreground",children:"Grupo de usuários"}),3===t.type&&e("p",{className:"text-xs text-muted-foreground",children:"Local"}),e("p",{className:"text-sm font-medium break-words",children:r}),e(ry,{approver:t})]})}function iy({config:t,isLoading:r=!1,onClose:n,onApprove:s,onDefineApprover:l,onRefreshSteps:c,availableApprovers:d=[],isLoadingApprovers:u=!1}){const[m,h]=i(!1),[p,f]=i(!1),[g,v]=i(""),[x,b]=i(""),[y,N]=i(!1),[w,C]=i(""),k=r||m,_=o((e,a)=>{v(e),b(a??""),f(!0)},[]),A=o(async e=>{f(!1),h(!0);if(!await s(t.associationId,{stepApproverId:g,...e}))return _(g,e.observation),void h(!1);n(),h(!1)},[t.associationId,g,s,n,_]),D=o(e=>{C(e),N(!0)},[]),P=o(async e=>{N(!1),h(!0),await l(t.associationId,w,e),await(c?.(t.associationId)),h(!1)},[t.associationId,w,l,c]),E=t.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],T=(e,a)=>t.canApprove&&e.isCurrentStep&&a.approverId&&!a.date&&a.canApprove,I=(e,a)=>!t.flowReproved&&e.isCurrentStep&&1===a.type&&a.canApprove&&(!a.approverId||a.isToBeDefined);return a("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[a("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:t.color},children:[e(es,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:e(S,{className:"h-5 w-5"})}),e("span",{className:"text-lg font-medium",children:t.title})]}),k?e(oo,{isLoading:!0,type:"spinner",className:"flex-1",children:e("div",{})}):a("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[t.approvalFlowInfo.length>0&&e("div",{className:"space-y-1",children:t.approvalFlowInfo.map((a,t)=>e("div",{className:Ki("flex items-center gap-1.5 text-sm",a.color&&"rounded-lg px-2 py-1"),style:a.color?{color:a.color,backgroundColor:a.backgroundColor}:void 0,children:a.title?`${a.title}: ${a.value}`:a.value},t))}),e("hr",{className:"border-border"}),t.approvalFlowSteps.map(r=>a("div",{className:Ki("space-y-2",(!r.isCurrentStep||t.flowReproved)&&"opacity-50"),children:[a("p",{className:"font-semibold text-sm",children:[r.index,". Etapa: ",r.name]}),r.description&&e("p",{className:"text-sm text-muted-foreground break-words",children:e(ay,{text:r.description})}),r.returnDate&&a("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[a("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),a("span",{className:"text-xs text-muted-foreground",children:[r.returnUserName," em ",ey(r.returnDate)]})]}),r.returnObservation&&e("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:e(ay,{text:r.returnObservation})})]}),r.approvers.map(t=>a("div",{className:"p-2 space-y-1",children:[a("div",{className:"flex items-center justify-between gap-2",children:[a("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e(ty,{approver:t}),e(ny,{approver:t})]}),T(r,t)&&e(es,{size:"sm",onClick:()=>_(t.id),children:"Aprovar"}),I(r,t)&&e(es,{size:"sm",variant:"outline",onClick:()=>D(t.id),children:"Selecionar"})]}),t.observation&&e("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e(ay,{text:t.observation})}),t.returnObservation&&e("p",{className:"text-sm text-muted-foreground break-words ml-11",children:e(ay,{text:t.returnObservation})})]},t.id))]},r.id))]}),e(Jb,{open:p,onOpenChange:f,returnSteps:t.returnSteps,initialObservation:x,title:t.approveDialogTitle,descriptions:t.approveDialogDescriptions,setDefaultApproverOnInit:t.approveDialogSetDefaultApproverOnInit,onSubmit:A}),e(Zb,{open:y,onOpenChange:N,approvers:d,isLoading:u,ignoreUserIds:E,onSubmit:P})]})}var sy,oy;function ly({users:t,value:r,onChange:n,disabled:l=!1,placeholder:c="Buscar membro da equipe...",confirmRemoval:d=!0,confirmTitle:u="Remover da equipe",confirmMessage:m="Tem certeza que deseja remover este membro da equipe?",emptyMessage:h="Nenhum membro na equipe",className:p}){const[f,g]=i(""),[v,x]=i(!1),[b,y]=i(null),N=s(()=>new Set(r),[r]),w=s(()=>t.filter(e=>N.has(e.id)),[t,N]),C=s(()=>t.filter(e=>!N.has(e.id)).map(e=>({value:e.id,label:e.name})),[t,N]),k=o(e=>{e&&!N.has(e)&&(n([...r,e]),g(""))},[r,n,N]),_=o(e=>{d?(y(e),x(!0)):n(r.filter(a=>a!==e))},[r,n,d]),A=o(()=>{b&&n(r.filter(e=>e!==b)),x(!1),y(null)},[b,r,n]);return a("div",{className:Ki("space-y-3",p),children:[e("div",{className:"flex items-start gap-3",children:e("div",{className:"flex-1",children:e(Wo,{options:C,value:f,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";g(a),a&&k(a)},placeholder:c,searchPlaceholder:"Buscar...",disabled:l})})}),a("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),e("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:w.length})]}),w.length>0?e("div",{className:"space-y-2",children:w.map(t=>a("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[a(cu,{className:"h-8 w-8 shrink-0",children:[t.avatar&&e(du,{src:t.avatar,alt:t.name}),e(uu,{className:"text-xs",children:t.name?.substring(0,2).toUpperCase()})]}),e("div",{className:"flex-1 min-w-0",children:e("p",{className:"text-sm font-medium truncate",title:t.name,dangerouslySetInnerHTML:{__html:t.title||t.name}})}),a("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[t.roleName&&a("span",{className:"flex items-center gap-1",children:[e(de,{className:"h-3.5 w-3.5"}),e("span",{className:"truncate max-w-[120px]",children:t.roleName})]}),t.placeName&&a("span",{className:"flex items-center gap-1",children:[e(je,{className:"h-3.5 w-3.5"}),e("span",{className:"truncate max-w-[120px]",children:t.placeName})]}),e("button",{type:"button",className:Ki("text-muted-foreground hover:text-destructive transition-colors",l&&"opacity-50 pointer-events-none"),onClick:()=>!l&&_(t.id),title:"Remover",children:e(S,{className:"h-4 w-4"})})]})]},t.id))}):a("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[e(qe,{className:"h-12 w-12 mb-2 opacity-30"}),e("p",{className:"text-sm",children:h})]}),e(Cs,{open:v,onOpenChange:x,children:a(Ps,{className:"sm:max-w-[400px]",children:[e(Es,{children:e(Ms,{children:u})}),e("p",{className:"text-sm text-muted-foreground",children:m}),a(Is,{children:[e(es,{variant:"ghost",onClick:()=>x(!1),children:"Cancelar"}),e(es,{variant:"destructive",onClick:A,children:"Remover"})]})]})})]})}(oy=sy||(sy={}))[oy.ApprovalFlow=1]="ApprovalFlow",oy[oy.Association=2]="Association";export{Cr as AUTH_CONFIG,eu as AccessDeniedDialog,iu as Accordion,lu as AccordionContent,su as AccordionItem,ou as AccordionTrigger,as as ActionButton,as as ActionMenu,bc as ActionMenuItems,lb as ActionPlanAttachmentsTab,rb as ActionPlanCommentsTab,tb as ActionPlanCostTab,Hx as ActionPlanGeneralTab,ib as ActionPlanHistoryTab,db as ActionPlanPage,ab as ActionPlanPredecessorsTab,Jx as ActionPlanProgressDialog,Zx as ActionPlanProgressTab,Wx as ActionPlanStatusBadge,jp as AggregationType,ud as Alert,hd as AlertDescription,ms as AlertDialog,Ns as AlertDialogAction,ws as AlertDialogCancel,gs as AlertDialogContent,ys as AlertDialogDescription,xs as AlertDialogFooter,vs as AlertDialogHeader,fs as AlertDialogOverlay,ps as AlertDialogPortal,bs as AlertDialogTitle,hs as AlertDialogTrigger,md as AlertTitle,ld as AliasRedirect,od as AliasRouteGuard,Bp as AnalysisFunctionality,iv as AppHeader,gv as AppLayout,fv as AppSidebar,sy as ApprovalFlowReturnStep,iy as ApprovalSidenav,Jb as ApproveDialog,Qb as AuditTrailDetails,Fb as AuditTrailFilter,Xb as AuditTrailPage,vl as AuthErrorInterceptor,Ll as AuthProvider,Tl as AuthService,Wo as AutoComplete,cu as Avatar,uu as AvatarFallback,du as AvatarImage,no as Badge,Wc as BaseForm,rm as Blockquote,bv as BodyContent,mu as Breadcrumb,xu as BreadcrumbEllipsis,pu as BreadcrumbItem,fu as BreadcrumbLink,hu as BreadcrumbList,gu as BreadcrumbPage,vu as BreadcrumbSeparator,xg as BurndownPanel,es as Button,yu as ButtonGroup,$x as CLOSED_STATUSES,kr as CRUD_CONFIG,jf as CURRENCY_FIELDS,Nu as Calendar,pd as CallbackPage,is as Card,cs as CardContent,ls as CardDescription,ds as CardFooter,ss as CardHeader,Ql as CardSkeleton,os as CardTitle,hg as CartesianPanel,Fh as ChartContainer,Bh as ChartLegend,$h as ChartLegendContent,Uh as ChartStyle,jh as ChartTooltip,Oh as ChartTooltipContent,ao as Checkbox,Md as Collapsible,Ld as CollapsibleContent,Rd as CollapsibleTrigger,jc as ColorPicker,Zo as ComboTree,Wo as Combobox,Mo as Command,Ro as CommandDialog,Fo as CommandEmpty,Uo as CommandGroup,Lo as CommandInput,Oo as CommandItem,zo as CommandList,jo as CommandSeparator,Bo as CommandShortcut,xv as ContentContainer,nc as ContextMenu,pc as ContextMenuCheckboxItem,mc as ContextMenuContent,sc as ContextMenuGroup,hc as ContextMenuItem,gc as ContextMenuLabel,oc as ContextMenuPortal,cc as ContextMenuRadioGroup,fc as ContextMenuRadioItem,vc as ContextMenuSeparator,xc as ContextMenuShortcut,lc as ContextMenuSub,uc as ContextMenuSubContent,dc as ContextMenuSubTrigger,ic as ContextMenuTrigger,nu as CoreProviders,Pc as CrudActionBar,$g as CrudActionMenu,Og as CrudGrid,Zc as CrudPageInternal,Gc as CrudPagination,Vg as CrudPrimitiveFilterBar,Hc as CrudPrimitivePagination,Bg as CrudPrimitiveTable,zc as CrudTable,Lb as CustomFormFields,Cx as D4SignWidget,Uf as DASHBOARD_STORAGE_KEYS,Di as DATETIME_FORMATS,Ox as DEFAULT_ACTION_TYPES,Ti as DEFAULT_DATETIME_FORMAT,Ei as DEFAULT_LOCALE,Ii as DEFAULT_TIMEZONE,Ug as DashboardForm,cf as DashboardFormTab,$p as DashboardFunctionality,jg as DashboardGeneralView,_g as DashboardGrid,hf as DashboardLanguage,Ig as DashboardList,qp as DashboardListType,Hp as DashboardPageTime,Yp as DashboardPanelDimension,Jp as DashboardPanelOrderBy,Qp as DashboardPanelOrderByType,ef as DashboardPanelPeriod,Ag as DashboardPanelRenderer,tf as DashboardPanelType,uf as DashboardShareType,nf as DashboardUpdateTime,Dg as DashboardView,of as DashboardViewType,Vg as DataFilterBar,wu as DataList,Hc as DataPagination,Bg as DataTable,Cu as DatePicker,Cs as Dialog,Ts as DialogBody,Ss as DialogClose,Ps as DialogContent,Rs as DialogDescription,Is as DialogFooter,Es as DialogHeader,As as DialogOverlay,_s as DialogPortal,Ms as DialogTitle,ks as DialogTrigger,Po as DisabledMenuItem,kx as DocumentSigner,ku as Drawer,Au as DrawerClose,Pu as DrawerContent,Mu as DrawerDescription,Tu as DrawerFooter,Eu as DrawerHeader,Du as DrawerOverlay,Su as DrawerPortal,Iu as DrawerTitle,_u as DrawerTrigger,co as DropdownMenu,yo as DropdownMenuCheckboxItem,xo as DropdownMenuContent,mo as DropdownMenuGroup,bo as DropdownMenuItem,wo as DropdownMenuLabel,ho as DropdownMenuPortal,fo as DropdownMenuRadioGroup,No as DropdownMenuRadioItem,Co as DropdownMenuSeparator,ko as DropdownMenuShortcut,po as DropdownMenuSub,vo as DropdownMenuSubContent,go as DropdownMenuSubTrigger,uo as DropdownMenuTrigger,Rx as EAttachmentItemStatus,fb as ECustomFormFieldType,vb as EFieldViewMode,bb as ESelectionFieldDataSource,Ex as ETaskPlanAssociationType,Dx as ETaskPlanPriority,Sx as ETaskPlanStatus,Ix as ETaskPlanTypeProgress,np as ElectronicSignatureDialog,tc as EllipsisText,kv as EmailService,ac as EmptyState,Wo as EntitySelect,zd as ErrorBoundary,tp as ExportDialog,Jh as ExportFormat,ub as FORBIDDEN_FILE_TYPES,mp as FilePrintType,dp as FileViewerType,Jc as FilterBar,Ls as Form,$s as FormControl,Db as FormDateField,Vs as FormDescription,Fs as FormField,Os as FormItem,Bs as FormLabel,qs as FormMessage,Mb as FormMultiSelectionField,Tb as FormNumericField,Rb as FormQuestionsField,Ib as FormSingleSelectionField,Xl as FormSkeleton,Ab as FormTextField,Pb as FormTimeField,Eb as FormUrlField,zu as Grid,Gu as H1,Yu as H2,Ku as H3,Qu as H4,Jl as HeaderSkeleton,Fu as HoverCard,ju as HoverCardContent,Uu as HoverCardTrigger,Bc as IconPicker,Cp as IframeDialog,ox as ImageEditor,lx as ImageRenderer,tm as InlineCode,ts as Input,Ou as InputGroup,$u as InputGroupAddon,qu as InputGroupButton,Wu as InputGroupInput,Hu as InputGroupTextarea,Of as LINK_PROPERTIES,Ir as LOGO_CONFIG,ns as Label,Zu as Large,Ju as Lead,Gv as LeadershipDialog,Hv as LeadershipForm,Qv as LeadershipPage,nm as List,dg as ListPanel,oo as LoadingState,Dd as LocaleProvider,fd as LoginPage,Mr as MESSAGES,qd as MODULES_DATA,Ff as MONTHS_MAP,Sv as ManageAccessModal,yg as MatrixRiskPanel,ff as MatrixViewType,Ch as Menubar,Ph as MenubarCheckboxItem,Ah as MenubarContent,bh as MenubarGroup,Dh as MenubarItem,Th as MenubarLabel,xh as MenubarMenu,yh as MenubarPortal,wh as MenubarRadioGroup,Eh as MenubarRadioItem,Ih as MenubarSeparator,Mh as MenubarShortcut,Nh as MenubarSub,Sh as MenubarSubContent,_h as MenubarSubTrigger,kh as MenubarTrigger,mv as ModalStateProvider,tu as ModuleAccessGuard,Gd as ModuleGrid,ru as ModuleOfferContent,Td as ModuleProvider,Yd as ModulesContent,Zd as ModulesDialog,Vd as ModulesFooterCards,Wo as MultiSelect,Tp as MultiselectPermissions,am as Muted,im as NavigationMenu,dm as NavigationMenuContent,hm as NavigationMenuIndicator,om as NavigationMenuItem,um as NavigationMenuLink,sm as NavigationMenuList,cm as NavigationMenuTrigger,mm as NavigationMenuViewport,Zg as NavigationProvider,lg as NumericPanel,Qh as OnboardingDialog,wp as OnlineEditorDialog,Xu as P,Bx as PRIORITIES,xr as PROD_PROJECT_ID,Vx as PROGRESS_ALLOWED_STATUSES,pm as PageBreadcrumb,vd as PageMetadataProvider,gm as Pagination,vm as PaginationContent,wm as PaginationEllipsis,xm as PaginationItem,bm as PaginationLink,Nm as PaginationNext,ym as PaginationPrevious,Lf as PaletteType,rg as PanelError,tg as PanelHeader,vf as PanelItemsPerPanel,ng as PanelLoader,ig as PanelNoData,bf as PanelSortType,Nf as PanelState,sg as PanelUnavailable,vg as ParetoPanel,bg as PerformancePanel,gg as PiePanel,Av as PlaceCard,Dv as PlacesList,_f as PlanType,Eo as Popover,Io as PopoverContent,To as PopoverTrigger,Cm as Progress,id as ProtectedRoute,Tr as QUALIEX_CONFIG,Er as QUERY_KEYS,_l as QualiexEnrichmentService,xl as QualiexErrorInterceptor,qc as QualiexUserField,Af as QueriesContextType,Pf as QueriesShareType,Tf as QuickFilterDashboard,km as RadioGroup,_m as RadioGroupItem,Sb as ReadOnlyTextField,Fp as ReportRequestList,Ip as ReportRequestStatus,Dm as ResizableHandle,Am as ResizablePanel,Sm as ResizablePanelGroup,Hh as RichTextEditor,Mf as RiskCriticality,_r as SEARCH_CONFIG,zx as STATUS_COLORS,jx as STATUS_LABELS,Ux as STATUS_MAP,Fx as STATUS_TEXT_COLORS,Ai as SUPPORTED_LOCALES,Ho as ScrollArea,Go as ScrollBar,Ws as Select,Zb as SelectApproverDialog,Xs as SelectContent,Hs as SelectGroup,Zs as SelectItem,Js as SelectLabel,Qs as SelectScrollDownButton,Ks as SelectScrollUpButton,Wo as SelectSearch,eo as SelectSeparator,Ys as SelectTrigger,Gs as SelectValue,us as Separator,Pm as Sheet,Fm as SheetBody,Tm as SheetClose,Lm as SheetContent,Om as SheetDescription,Um as SheetFooter,zm as SheetHeader,Mm as SheetOverlay,Im as SheetPortal,jm as SheetTitle,Em as SheetTrigger,Wm as Sidebar,ov as SidebarActionTrigger,Zm as SidebarContent,Xm as SidebarFooter,eh as SidebarGroup,th as SidebarGroupAction,rh as SidebarGroupContent,ah as SidebarGroupLabel,vv as SidebarHeader,Km as SidebarInput,Ym as SidebarInset,nv as SidebarLogo,nh as SidebarMenu,lh as SidebarMenuAction,ch as SidebarMenuBadge,oh as SidebarMenuButton,ih as SidebarMenuItem,dh as SidebarMenuSkeleton,uh as SidebarMenuSub,hh as SidebarMenuSubButton,mh as SidebarMenuSubItem,qm as SidebarProvider,Gm as SidebarRail,Jm as SidebarSeparator,Zl as SidebarSkeleton,Hm as SidebarTrigger,_x as SignConfigForm,wx as SignWidget,pb as SingleFileUpload,$o as Skeleton,ph as Slider,em as Small,lo as SonnerToaster,so as Spinner,Xh as SplitButton,Xc as Stack,ip as StepSelector,ip as Stepper,Up as StimulsoftViewer,$c as Switch,Pi as TIMEZONES,vh as TabPageContent,gh as TabPageHeader,fh as TabPageLayout,Bl as Table,Vl as TableBody,Yl as TableCaption,Gl as TableCell,ql as TableFooter,Hl as TableHead,$l as TableHeader,rc as TableResizeHandle,Wl as TableRow,yc as TableRowActions,Kl as TableSkeleton,Fd as Tabs,Od as TabsContent,Ud as TabsList,jd as TabsTrigger,ly as TeamSelector,kp as TermsOfUseDialog,_p as TermsOfUseViewer,cg as TextPanel,to as Textarea,rp as Timepicker,lo as Toaster,_c as Toggle,Ac as ToggleGroup,Dc as ToggleGroupItem,cl as TokenManager,el as TokenService,So as Tooltip,Do as TooltipContent,_o as TooltipProvider,Ao as TooltipTrigger,Zo as TreeSelect,Yg as TreeTable,tc as TruncatedCell,cp as UpdatesNotification,Dp as UsersGroupsSelector,ix as VideoEditor,sx as VideoRenderer,yp as ViewerDialog,Cf as VisualizationType,kd as addAppTranslations,zr as assets,ro as badgeVariants,$b as buildDetailRows,Tv as buildHierarchy,Yi as buildModuleUrl,Jf as buildPlacesTree,bp as buildWopiUrl,bu as buttonGroupVariants,Zi as buttonVariants,cx as calculateAspectRatio,Gb as camelToDash,Ki as cn,ed as createCrudPage,Qg as createCrudRoutingConfig,Kg as createRoutingHandlers,Dl as createService,ad as createSimpleSaveHandler,Ul as createSimpleService,Rr as createTranslatedMessages,Xf as currencyFormatter,Xi as debounce,Nl as deriveEmailField,yl as deriveNameField,wl as deriveUsernameField,ji as detectBrowserLocale,$i as detectBrowserPreferences,Oi as detectBrowserTimezone,rx as detectVideoProvider,_v as emailService,dl as errorService,mx as extractImageFileName,Qf as extractNumberFromCurrency,ex as extractVimeoId,Jv as extractYouTubeId,Ev as filterAndPromoteOrphans,Ri as findDatetimeFormat,Mi as findLocale,Li as findTimezone,Iv as flattenTree,mb as formatBytes,Hi as formatCurrency,Wi as formatDate,qi as formatDatetime,hx as formatFileSize,Qx as formatTime,Kx as formatTimeProgress,td as generateCrudConfig,wg as getDefaultPanelSize,Nr as getEnvironmentConfig,Nb as getFieldValue,hb as getFileExtension,Cb as getFormFieldValues,Wf as getLinkFromRow,Cg as getMinPanelSize,gp as getOnlineViewerType,Xx as getProgressColor,Pr as getQualiexApiUrl,pl as getSupabaseClient,fp as getViewerType,xp as getWopiViewer,Gi as handleExternalLink,Bi as inferDatetimeFormat,Bu as inputGroupAddonVariants,Vu as inputGroupButtonVariants,Kf as isCurrency,Dr as isDevEnvironment,wr as isDevSupabaseProject,ux as isImageUrl,Sr as isLovablePreview,Vf as isNullOrEmptyField,Fi as isValidDatetimeFormat,zi as isValidLocale,Ui as isValidTimezone,yx as loadClicksignScript,Fr as logoSrc,lm as navigationMenuTriggerStyle,nx as normalizeVideoUrl,ax as normalizeVimeoUrl,Zv as normalizeYouTubeUrl,tx as parseIframeSrc,Pv as placeService,jb as processTrails,qf as processUrl,bl as qualiexApi,dx as resizeKeepingAspect,Cl as resolveFieldMappings,tv as resolvePageTitle,kb as setFormFieldValues,yd as setupQualiexCore,wb as shouldShowField,Ar as shouldUseDevTokens,xx as signService,Ji as slugify,Ur as smallLogoSrc,Bf as sortByMonthYear,Hf as toQueryString,kc as toggleVariants,Qi as trimTextFields,qx as useActionPlan,Yx as useActionPlanProgress,yv as useActiveModules,sd as useAliasFromUrl,zl as useAuth,Fc as useBaseForm,Cc as useColumnResize,zv as useCreateMultipleLeadersMutation,Lv as useCreateSingleLeaderMutation,Fl as useCrud,rv as useDebounce,Jd as useDerivedContractedModules,Us as useFormField,pv as useHasOpenModal,Cv as useI18nFormatters,Ol as useIsMobile,Mv as useLeadershipApi,Pd as useLocale,jl as useMediaQuery,Xv as useMediaUpload,hv as useModalState,Xd as useModuleAccess,Id as useModuleConfig,ev as useNavigation,bd as usePageMetadata,xd as usePageMetadataContext,av as usePageTitle,sv as usePermissionQuery,Vc as useQualiexUsers,Uv as useRemoveLeaderMutation,fm as useRouteBreadcrumbs,Nv as useRowResize,Vm as useSidebar,dv as useSidebarResize,px as useSignConfig,jv as useSyncSubordinatesMutation,Fv as useUpdateLeaderMutation,lp as useUpdatesNotification,wv as useWizard,_b as validateFields};